#!/usr/bin/env bash
# Deploys origin/main to one instance on SRVMPHTAT2MEC.
#
#   scripts/deploy.sh <instance> [--rebuild]
#   instance: prod | nomad | demo
#
# Run by the manual `deploy:*` jobs in .gitlab-ci.yml over SSH, or by hand on
# the server. The CI key is pinned to this script in authorized_keys
# (command="..."), so the instance name then arrives in $SSH_ORIGINAL_COMMAND
# rather than as an argument — see DEPLOY.md.
#
# What it does, stopping at the first failure:
#   1. refuses if the checkout has local edits to tracked files — except the
#      client's own logo/favicon on branded checkouts, which it sets aside and
#      puts back (they blocked `git pull` on nomad on 2026-09-07). Mode-only
#      changes don't count: docker/entrypoint.sh chmods bootstrap/cache on
#      every start, flipping its tracked .gitignore to 755 (nomad, 2026-10-27)
#   2. backs the database up (scripts/backup_db.sh)
#   3. fast-forwards to origin/main
#   4. `composer install` if composer.lock changed
#   5. rebuilds the app image if the Dockerfile or docker/php/ changed (or
#      --rebuild) — a pull alone never picks up php.ini changes, which is how
#      display_errors=On outlived its fix for weeks
#   6. `artisan db:migrate --force` — refuses on an un-baselined instance
#   7. `artisan optimize:clear`, then `artisan optimize` to rebuild the
#      config/route/view/event caches — without them every request re-reads
#      all of config/ and re-registers all of routes/web.php, which the
#      header search's per-keystroke requests felt most. Config is baked in
#      at this point: an .env edit on the server needs `artisan optimize`
#      (or a redeploy) to take effect
#   8. checks /login.php answers 200
#
# The app container bind-mounts the checkout, so steps 3-4 take effect
# without a restart; only step 5 recreates the container.
#
# Everything lives inside main(): this script updates its own checkout in
# step 3, and bash reads a script as it runs — a function body is parsed
# whole before any of it executes.

set -euo pipefail

main() {
    local instance="${1:-${SSH_ORIGINAL_COMMAND:-}}"
    local rebuild=0

    # SSH_ORIGINAL_COMMAND carries everything the CI job sent ("prod --rebuild").
    # read -a, not words=($x): no glob expansion of whatever arrived.
    local -a words=()
    read -ra words <<<"$instance" || true
    instance="${words[0]:-}"
    for w in "${words[@]:1}" "${@:2}"; do
        case "$w" in
            --rebuild) rebuild=1 ;;
            *) die "Unknown argument: $w" ;;
        esac
    done

    local dir compose project url
    case "$instance" in
        prod)  dir=/var/www/html;  compose=docker-compose.yml;         project=html;         url=https://axioma-study.kz/login.php ;;
        nomad) dir=/var/www/nomad; compose=docker-compose.branded.yml; project=axioma-nomad; url=https://nomad.axicrm.com/login.php ;;
        demo)  dir=/var/www/demo;  compose=docker-compose.demo.yml;    project=axioma-demo;  url=https://demo.axioma-study.kz/login.php ;;
        *) die "Usage: deploy.sh <prod|nomad|demo> [--rebuild]" ;;
    esac

    # Lets the branching logic be exercised against a scratch checkout.
    dir="${DEPLOY_DIR_OVERRIDE:-$dir}"

    [ -d "$dir/.git" ] || die "$dir is not a git checkout"
    cd "$dir"
    [ -f "$compose" ] || die "$dir has no $compose — check this instance's compose file before deploying it"

    local -a dc=(docker compose -f "$dir/$compose" -p "$project")

    step "Deploying $instance ($dir, project $project)"

    local branch
    branch="$(git rev-parse --abbrev-ref HEAD)"
    [ "$branch" = "main" ] || die "$dir is on branch '$branch', not main"

    git fetch --quiet origin main

    # 1. Local edits. The client logo/favicon are the one expected kind.
    local keep_dir
    keep_dir="$(mktemp -d)"
    local -a kept=()
    local f
    while IFS= read -r f; do
        [ -n "$f" ] || continue
        case "$f" in
            images/logo.png|images/favicon/*)
                mkdir -p "$keep_dir/$(dirname "$f")"
                cp -p "$f" "$keep_dir/$f"
                kept+=("$f")
                ;;
            *) die "Tracked file modified in $dir: $f — commit, revert or move it before deploying" ;;
        esac
    done < <(git -c core.fileMode=false diff --name-only HEAD)

    local old new
    old="$(git rev-parse HEAD)"
    new="$(git rev-parse origin/main)"

    # 2. Backup — before anything changes. DDL can't be rolled back.
    step "Backing up the database"
    scripts/backup_db.sh "$project" --compose-file "$dir/$compose"
    # Same BACKUP_DIR backup_db.sh resolved, from this checkout's own .env.
    local backup_dir backup
    backup_dir="$(grep -E '^BACKUP_DIR=' .env 2>/dev/null | tail -1 | cut -d= -f2- | tr -d '\r"' || true)"
    backup="$(ls -1t "${backup_dir:-/var/backups/axioma}/$project"/*.sql.gz 2>/dev/null | head -1 || true)"
    [ -n "$backup" ] || die "backup_db.sh reported success but no dump was found"

    # 3. Code.
    if [ "$old" = "$new" ]; then
        step "Already at ${new:0:8}"
    else
        step "Updating ${old:0:8} -> ${new:0:8}"
        if [ ${#kept[@]} -gt 0 ]; then
            git checkout -- "${kept[@]}"
        fi
        git -c core.fileMode=false merge --ff-only --quiet origin/main || die "origin/main does not fast-forward from ${old:0:8}"
        git log --oneline "$old..$new" | sed 's/^/    /'
    fi

    for f in "${kept[@]}"; do
        cp -p "$keep_dir/$f" "$f"
        echo "    restored client file $f"
    done
    rm -rf "$keep_dir"

    local changed
    changed="$(git diff --name-only "$old" "$new")"

    # 4. Dependencies.
    if grep -qx 'laravel/composer.lock' <<<"$changed"; then
        step "composer.lock changed — installing"
        "${dc[@]}" exec -T app composer install --working-dir=/var/www/html/laravel --no-interaction --optimize-autoloader
    fi

    # 5. Image.
    if [ "$rebuild" -eq 1 ] || grep -qE '^(Dockerfile|docker/php/|docker/entrypoint\.sh)' <<<"$changed"; then
        step "Rebuilding the app image"
        "${dc[@]}" up -d --build app
        wait_for_app "${dc[@]}"
    fi

    # 6. Schema.
    step "Applying migrations"
    if ! "${dc[@]}" exec -T app php /var/www/html/laravel/artisan db:migrate --force; then
        echo
        echo "Migrations failed. The code is already at ${new:0:8}."
        echo "Backup taken before this deploy: $backup"
        echo "Restore with: scripts/restore_db.sh $project $backup --compose-file $dir/$compose"
        exit 1
    fi

    # 7. Caches.
    "${dc[@]}" exec -T app php /var/www/html/laravel/artisan optimize:clear >/dev/null
    # As www-data: the compiled views land in storage/framework/views, which
    # Apache (www-data) keeps writing to; root-owned 0644 files there would
    # make any later recompile of them fail.
    "${dc[@]}" exec -T -u www-data app php /var/www/html/laravel/artisan optimize >/dev/null

    # 8. Smoke check.
    step "Checking $url"
    local code=000 i
    for i in 1 2 3 4 5; do
        code="$(curl -sS -o /dev/null -w '%{http_code}' --max-time 15 "$url" || true)"
        [ "$code" = "200" ] && break
        sleep 3
    done
    if [ "$code" != "200" ]; then
        echo "$url answered $code, not 200."
        echo "Backup taken before this deploy: $backup"
        exit 1
    fi

    step "Done: $instance is at ${new:0:8} ($url -> 200)"
}

step() { printf '\n== %s\n' "$*"; }

die() { printf 'deploy: %s\n' "$*" >&2; exit 1; }

wait_for_app() {
    local i
    for i in $(seq 1 30); do
        if "$@" exec -T app true 2>/dev/null; then
            return 0
        fi
        sleep 2
    done
    die "app container did not come back after the rebuild"
}

main "$@"
exit
