#!/usr/bin/env bash
# FTPS deploy (doc 12 §8): CI builds the artifact and uploads it over FTPS —
# no developer FTPs files by hand; with 31 developers that is how production
# drifts from main. After upload, pending migrations are applied through the
# token-protected endpoint (never manually).
#
# Required environment:
#   FTPS_HOST, FTPS_USER, FTPS_PASSWORD, FTPS_REMOTE_DIR
# Optional (post-deploy migration + verification):
#   APP_URL, MIGRATION_TOKEN
set -euo pipefail
cd "$(dirname "$0")/.."

: "${FTPS_HOST:?FTPS_HOST is required}"
: "${FTPS_USER:?FTPS_USER is required}"
: "${FTPS_PASSWORD:?FTPS_PASSWORD is required}"
: "${FTPS_REMOTE_DIR:?FTPS_REMOTE_DIR is required}"

src="dist/build"
[ -d "$src" ] || { echo "dist/build not found — run build/release.sh first" >&2; exit 1; }

if command -v lftp >/dev/null 2>&1; then
    lftp -u "$FTPS_USER,$FTPS_PASSWORD" "ftps://$FTPS_HOST" -e "
        set ftp:ssl-force true;
        set ftp:ssl-protect-data true;
        mirror -R --parallel=4 $src $FTPS_REMOTE_DIR;
        bye"
else
    # curl fallback: slower, one file at a time, but dependency-free.
    find "$src" -type f | while read -r file; do
        remote="${file#"$src"/}"
        curl -sS --ssl-reqd --ftp-create-dirs \
            -T "$file" \
            -u "$FTPS_USER:$FTPS_PASSWORD" \
            "ftp://$FTPS_HOST/$FTPS_REMOTE_DIR/$remote"
    done
fi
echo "Upload complete."

if [ -n "${APP_URL:-}" ] && [ -n "${MIGRATION_TOKEN:-}" ]; then
    echo "Applying migrations…"
    curl -fsS -X POST -H "X-Admin-Token: $MIGRATION_TOKEN" "$APP_URL/admin/migrate"
    echo
    echo "Verifying /health…"
    curl -fsS "$APP_URL/health"
    echo
fi
