#!/usr/bin/env bash
# Private repo: migration script'ini Railway Faunamix konteynerine yazar.
#
# Sorunlar:
# - Tek satırda ~3K+ karakter: argv kesimi → gzip "unexpected end of file".
# - Birkaç ayrı railway ssh: farklı kutular → bozuk gzip.
# - Uzakta "set -e" bazen "set" ile "-e" ayrılırsa POSIX sh önce argümansız set çalıştırır
#   → tüm ortam (DB_PASS, SMTP vb.) stdout'a dökülür. Bu yüzden set -e yok; || exit 1.
#
# Çözüm: TEK ssh; bash --noprofile --norc (giriş profili gürültüsü yok); çok satırlı script.
#
# Önkoşul: railway login, railway link → Faunamix
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SRC="$ROOT/scripts/run-database-migrations.sh"
# Uzak gövdede yollar sabit; "rm -f --" argv'de -- kaybı olabiliyor → -- kullanma.
# Uzun "bash -c '…'" argv'sinde Railway / katmanlar % ve printf'i bozabiliyor → gövdeyi base64 sarıp
# stdin ile ikinci bash'e ver (asıl komutlar argv'de değil, pipe'ta).
readonly REMOTE_DEST="/app/scripts/run-database-migrations.sh"

if [[ ! -f "$SRC" ]]; then
  echo "Eksik: $SRC"
  exit 1
fi

BYTES="$(wc -c <"$SRC" | tr -d ' ')"
GZB64="$(gzip -9cn <"$SRC" | base64 | tr -d '\n')"
blen=${#GZB64}
# Uzun satır railway ssh / -c ile kesilebilir → eksik parça → "base64: invalid input"; muhafazakâr parça.
step=768
total=$(((blen + step - 1) / step))

SSH=(railway ssh)
if [[ -n "${FAUNAMIX_RAILWAY_SERVICE:-}" ]]; then
  SSH=(railway ssh -s "$FAUNAMIX_RAILWAY_SERVICE")
fi

echo "Gönderiliyor: $SRC (${BYTES} byte → gzip+base64 ${blen} karakter, tek SSH, gövde base64+stdin, ${total} satır php, ${SSH[*]} …)"

# Konteynerde PHP var; parça yazımında % yok (Railway argv ile printf sorunu yok).
# Chunk gzip+base64 alfabesi; PHP tek tırnaklı stringde ' veya \ yok.
REMOTE_BODY=""
n=0
for ((i = 0; i < blen; i += step)); do
  chunk="${GZB64:i:step}"
  n=$((n + 1))
  if [[ "$n" -eq 1 ]]; then
    REMOTE_BODY="php -r \"file_put_contents('/tmp/faunamix-migrate.gz.b64', '${chunk}');\""
  else
    REMOTE_BODY+=$'\n'"php -r \"file_put_contents('/tmp/faunamix-migrate.gz.b64', '${chunk}', FILE_APPEND);\""
  fi
done

REMOTE_BODY+=$'\n'"b64n=\$(wc -c </tmp/faunamix-migrate.gz.b64 | tr -d ' '); test \"\$b64n\" -eq ${blen} || exit 1"
REMOTE_BODY+=$'\n'"base64 -d </tmp/faunamix-migrate.gz.b64 | gzip -dc >/app/scripts/run-database-migrations.sh || exit 1"
REMOTE_BODY+=$'\n'"chmod +x /app/scripts/run-database-migrations.sh || exit 1"
REMOTE_BODY+=$'\n'"rm -f /tmp/faunamix-migrate.gz.b64"
REMOTE_BODY+=$'\n'"n=\$(wc -c </app/scripts/run-database-migrations.sh | tr -d ' ')"
REMOTE_BODY+=$'\n'"test \"\$n\" -eq ${BYTES} || exit 1"
REMOTE_BODY+=$'\n'"echo \"Doğrulandı: \$n byte\""
REMOTE_BODY+=$'\n'"wc -c /app/scripts/run-database-migrations.sh"

PACK="$(printf '%s' "$REMOTE_BODY" | base64 | tr -d '\n')"

# Dış -c: tek satır, içinde % yok; asıl betik PACK decode sonrası stdin'den bash'te çalışır.
# shellcheck disable=SC2016
"${SSH[@]}" -- bash --noprofile --norc -c "echo \"${PACK}\" | base64 -d | bash --noprofile --norc"

echo "Tamam: ${REMOTE_DEST} güncellendi."
echo "Sonra: ${SSH[*]} -- bash --noprofile --norc -c 'FAUNAMIX_MIGRATE_FROM_ENV=1 /app/scripts/run-database-migrations.sh; echo EXIT:\$?'"
