#!/bin/bash
set -e

# Local wrapper for the upstream MONARC image entrypoint.
# The only behavioral change is making the initial admin seed idempotent.

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${GREEN}Starting MONARC FrontOffice setup...${NC}"

echo -e "${YELLOW}Waiting for MariaDB to be ready...${NC}"
while ! mysqladmin ping -h"${DBHOST}" -u"root" -p"${DBPASSWORD_ADMIN}" --silent 2>/dev/null; do
    echo "Waiting for MariaDB..."
    sleep 2
done
echo -e "${GREEN}MariaDB is ready!${NC}"

is_true() {
    case "$1" in
        1|true|yes|on) return 0 ;;
        *) return 1 ;;
    esac
}

trim() {
    local value="$1"
    value="${value#"${value%%[![:space:]]*}"}"
    value="${value%"${value##*[![:space:]]}"}"
    printf '%s' "$value"
}

php_escape_single_quoted() {
    local value="$1"
    value="${value//\\/\\\\}"
    value="${value//\'/\\\'}"
    printf '%s' "$value"
}

generate_language_config() {
    local default_language_definitions='fr:1:Français;en:2:English;de:3:Deutsch;nl:4:Nederlands;es:5:Spanish;ro:6:Romanian;it:7:Italian;ja:8:Japanese;pl:9:Polish;pt:10:Portuguese;zh:11:Chinese'
    local language_definitions="${MONARC_LANGUAGES:-$default_language_definitions}"
    local active_language_codes="${MONARC_ACTIVE_LANGUAGES:-}"
    local default_language_index="${MONARC_DEFAULT_LANGUAGE_INDEX:-1}"
    local language_entries=""
    local active_languages_php=""
    local default_index_found=0
    local entry code index label
    local -a parsed_codes=()
    local -a active_codes=()
    local -a language_items=()
    local -A seen_codes=()
    local -A seen_indexes=()

    if ! [[ "$default_language_index" =~ ^[0-9]+$ ]]; then
        echo -e "${RED}MONARC_DEFAULT_LANGUAGE_INDEX must be a positive integer.${NC}"
        exit 1
    fi

    IFS=';' read -r -a language_items <<< "$language_definitions"
    for entry in "${language_items[@]}"; do
        [ -z "$entry" ] && continue

        IFS=':' read -r code index label <<< "$entry"
        code="$(trim "$code")"
        index="$(trim "$index")"
        label="$(trim "$label")"

        if [ -z "$code" ] || [ -z "$index" ] || [ -z "$label" ]; then
            echo -e "${RED}Invalid MONARC_LANGUAGES entry: '$entry'. Expected format code:index:label.${NC}"
            exit 1
        fi

        if ! [[ "$index" =~ ^[0-9]+$ ]]; then
            echo -e "${RED}Invalid language index '$index' for code '$code'.${NC}"
            exit 1
        fi

        if [ -n "${seen_codes[$code]:-}" ]; then
            echo -e "${RED}Duplicate language code '$code' in MONARC_LANGUAGES.${NC}"
            exit 1
        fi

        if [ -n "${seen_indexes[$index]:-}" ]; then
            echo -e "${RED}Duplicate language index '$index' in MONARC_LANGUAGES.${NC}"
            exit 1
        fi

        seen_codes["$code"]=1
        seen_indexes["$index"]=1
        parsed_codes+=("$code")

        if [ "$index" = "$default_language_index" ]; then
            default_index_found=1
        fi

        language_entries+=$(printf "        '%s' => [\n            'index' => %s,\n            'label' => '%s',\n        ],\n" \
            "$(php_escape_single_quoted "$code")" \
            "$index" \
            "$(php_escape_single_quoted "$label")")
    done

    if [ ${#parsed_codes[@]} -eq 0 ]; then
        echo -e "${RED}MONARC_LANGUAGES did not define any languages.${NC}"
        exit 1
    fi

    if [ "$default_index_found" -ne 1 ]; then
        echo -e "${RED}MONARC_DEFAULT_LANGUAGE_INDEX=$default_language_index does not match any configured language index.${NC}"
        exit 1
    fi

    if [ -n "$active_language_codes" ]; then
        IFS=',' read -r -a active_codes <<< "$active_language_codes"
    else
        active_codes=("${parsed_codes[@]}")
    fi

    for code in "${active_codes[@]}"; do
        code="$(trim "$code")"
        [ -z "$code" ] && continue

        if [ -z "${seen_codes[$code]:-}" ]; then
            echo -e "${RED}MONARC_ACTIVE_LANGUAGES references unknown language code '$code'.${NC}"
            exit 1
        fi

        if [ -n "$active_languages_php" ]; then
            active_languages_php+=", "
        fi
        active_languages_php+="'$(php_escape_single_quoted "$code")'"
    done

    if [ -z "$active_languages_php" ]; then
        echo -e "${RED}MONARC_ACTIVE_LANGUAGES did not resolve to any configured language codes.${NC}"
        exit 1
    fi

    cat > config/autoload/languages.local.php <<EOF
<?php

return [
    /*
     * Language index maps to translated DB fields such as label{index} and name{index}.
     */
    'languages' => [
$language_entries    ],

    'defaultLanguageIndex' => $default_language_index,

    'activeLanguages' => [$active_languages_php],
];
EOF
}

write_runtime_config() {
    echo -e "${YELLOW}Writing runtime configuration...${NC}"

    cat > config/autoload/local.php <<EOF
<?php
\$appdir = getenv('APP_DIR') ? getenv('APP_DIR') : '/var/www/html/monarc';
\$string = file_get_contents(\$appdir.'/package.json');
if(\$string === FALSE) {
    \$string = file_get_contents('./package.json');
}
\$package_json = json_decode(\$string, true);

return [
    'doctrine' => [
        'connection' => [
            'orm_default' => [
                'params' => [
                    'host' => '${DBHOST}',
                    'user' => '${DBUSER_MONARC}',
                    'password' => '${DBPASSWORD_MONARC}',
                    'dbname' => '${DBNAME_COMMON}',
                ],
            ],
            'orm_cli' => [
                'params' => [
                    'host' => '${DBHOST}',
                    'user' => '${DBUSER_MONARC}',
                    'password' => '${DBPASSWORD_MONARC}',
                    'dbname' => '${DBNAME_CLI}',
                ],
            ],
        ],
    ],

    'appVersion' => \$package_json['version'],

    'checkVersion' => false,
    'appCheckingURL' => 'https://version.monarc.lu/check/MONARC',

    'email' => [
        'name' => 'MONARC',
        'from' => 'info@monarc.lu',
    ],

    'mospApiUrl' => 'https://objects.monarc.lu/api/',

    'monarc' => [
        'ttl' => 60,
        'salt' => '',
    ],

    'statsApi' => [
        'baseUrl' => 'http://stats-service:5005',
        'apiKey' => '${STATS_API_KEY:-}',
    ],

    'import' => [
        'uploadFolder' => '$appdir/data/import/files',
        'isBackgroundProcessActive' => false,
    ],
];
EOF

    generate_language_config
}

cd /var/www/html/monarc
write_runtime_config

if [ ! -f "/var/www/html/monarc/.docker-initialized" ]; then
    echo -e "${GREEN}First run detected, initializing application...${NC}"

    echo -e "${YELLOW}Installing Composer dependencies...${NC}"
    composer install --ignore-platform-req=php --no-interaction

    echo -e "${YELLOW}Creating module symlinks...${NC}"
    mkdir -p module/Monarc
    cd module/Monarc
    ln -sfn ./../../vendor/monarc/core Core
    ln -sfn ./../../vendor/monarc/frontoffice FrontOffice
    cd /var/www/html/monarc

    echo -e "${YELLOW}Setting up frontend repositories...${NC}"
    mkdir -p node_modules
    cd node_modules

    if [ ! -d "ng_client" ]; then
        git clone --config core.fileMode=false https://github.com/monarc-project/ng-client.git ng_client
    fi

    if [ ! -d "ng_anr" ]; then
        git clone --config core.fileMode=false https://github.com/monarc-project/ng-anr.git ng_anr
    fi

    cd /var/www/html/monarc

    echo -e "${YELLOW}Setting up databases...${NC}"
    DB_EXISTS=$(mysql -h"${DBHOST}" -u"root" -p"${DBPASSWORD_ADMIN}" -e "SHOW DATABASES LIKE '${DBNAME_CLI}';" | grep -c "${DBNAME_CLI}" || true)
    USE_BO_COMMON_ENABLED=0
    if is_true "${USE_BO_COMMON}"; then
        USE_BO_COMMON_ENABLED=1
    fi

    if [ "$DB_EXISTS" -eq 0 ]; then
        echo -e "${YELLOW}Creating databases...${NC}"
        mysql -h"${DBHOST}" -u"root" -p"${DBPASSWORD_ADMIN}" -e "CREATE DATABASE IF NOT EXISTS ${DBNAME_CLI} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;"

        if [ "$USE_BO_COMMON_ENABLED" -eq 0 ]; then
            mysql -h"${DBHOST}" -u"root" -p"${DBPASSWORD_ADMIN}" -e "CREATE DATABASE IF NOT EXISTS ${DBNAME_COMMON} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;"

            echo -e "${YELLOW}Populating common database...${NC}"
            export MYSQL_PWD="${DBPASSWORD_MONARC}"
            mysql -h"${DBHOST}" -u"${DBUSER_MONARC}" ${DBNAME_COMMON} < db-bootstrap/monarc_structure.sql
            mysql -h"${DBHOST}" -u"${DBUSER_MONARC}" ${DBNAME_COMMON} < db-bootstrap/monarc_data.sql
        else
            echo -e "${YELLOW}USE_BO_COMMON is enabled; skipping monarc_common creation and bootstrap.${NC}"
        fi
    fi

    echo -e "${YELLOW}Ensuring privileges for ${DBUSER_MONARC}...${NC}"
    mysql -h"${DBHOST}" -u"root" -p"${DBPASSWORD_ADMIN}" -e "GRANT ALL PRIVILEGES ON ${DBNAME_CLI}.* TO '${DBUSER_MONARC}'@'%';"
    if [ "$USE_BO_COMMON_ENABLED" -eq 0 ]; then
        mysql -h"${DBHOST}" -u"root" -p"${DBPASSWORD_ADMIN}" -e "GRANT ALL PRIVILEGES ON ${DBNAME_COMMON}.* TO '${DBUSER_MONARC}'@'%';"
    fi
    mysql -h"${DBHOST}" -u"root" -p"${DBPASSWORD_ADMIN}" -e "FLUSH PRIVILEGES;"

    if [ "$USE_BO_COMMON_ENABLED" -eq 1 ]; then
        COMMON_EXISTS=$(mysql -h"${DBHOST}" -u"root" -p"${DBPASSWORD_ADMIN}" -e "SHOW DATABASES LIKE '${DBNAME_COMMON}';" | grep -c "${DBNAME_COMMON}" || true)
        if [ "$COMMON_EXISTS" -eq 0 ]; then
            echo -e "${RED}USE_BO_COMMON is enabled, but ${DBNAME_COMMON} was not found on ${DBHOST}.${NC}"
            echo -e "${RED}Ensure the BackOffice database is reachable and contains ${DBNAME_COMMON}.${NC}"
            exit 1
        fi
    fi

    echo -e "${YELLOW}Building frontend and running DB migrations...${NC}"
    ./scripts/update-all.sh

    echo -e "${YELLOW}Ensuring initial admin seed...${NC}"
    ADMIN_EMAIL='admin@admin.localhost'
    ADMIN_EXISTS=$(mysql -N -s -h"${DBHOST}" -u"${DBUSER_MONARC}" -p"${DBPASSWORD_MONARC}" "${DBNAME_CLI}" -e "SELECT COUNT(*) FROM users WHERE email = '${ADMIN_EMAIL}';" 2>/dev/null || true)
    if [ "${ADMIN_EXISTS:-0}" -eq 0 ]; then
        echo -e "${YELLOW}Creating initial user and client...${NC}"
        php ./vendor/robmorgan/phinx/bin/phinx seed:run -c ./module/Monarc/FrontOffice/migrations/phinx.php
    else
        echo -e "${YELLOW}Initial admin already exists, skipping seed.${NC}"
    fi

    echo -e "${YELLOW}Setting permissions...${NC}"
    chown -R www-data:www-data /var/www/html/monarc/data
    chmod -R 775 /var/www/html/monarc/data

    touch /var/www/html/monarc/.docker-initialized
    echo -e "${GREEN}Initialization complete!${NC}"
else
    echo -e "${GREEN}Application already initialized, starting services...${NC}"
fi

exec "$@"
