#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

fail() { printf '%s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || fail 'Bu betiği systemd ve MariaDB erişimi olan root oturumunda çalıştırın.'
if [[ -x /opt/cpanel/ea-nodejs22/root/usr/bin/node ]]; then
  export PATH="/opt/cpanel/ea-nodejs22/root/usr/bin:$PATH"
fi
for cmd in node npm unzip rsync tar sha256sum mariadb mariadb-dump curl systemctl; do
  command -v "$cmd" >/dev/null || fail "Eksik komut: $cmd"
done
[[ $(node -p 'process.versions.node.split(".")[0]') == 22 ]] || fail 'Node.js 22.x gerekli.'

read -r -p 'Canlı API systemd servisi (.service dahil): ' api_unit
read -r -p 'Fal işleyicisi servisi (.service dahil), yoksa veya cron zaten durdurulduysa -: ' worker_unit
read -r -p 'panel.pembe.pink Document Root tam yolu: ' panel_input
read -r -p 'API ZIP tam yolu: ' api_zip_input
read -r -p 'Panel ZIP tam yolu: ' panel_zip_input

[[ $api_unit =~ ^[a-zA-Z0-9_.@-]+\.service$ && $api_unit != -* ]] || fail 'Geçerli API servis adı girin.'
systemctl is-active --quiet "$api_unit" || fail 'Girilen API servisi aktif değil.'
units=("$api_unit")
if [[ $worker_unit != '-' ]]; then
  [[ $worker_unit =~ ^[a-zA-Z0-9_.@-]+\.service$ && $worker_unit != -* && $worker_unit != "$api_unit" ]] ||
    fail 'Geçerli işleyici servis adı girin.'
  systemctl is-active --quiet "$worker_unit" || fail 'Girilen işleyici servisi aktif değil.'
  units+=("$worker_unit")
fi

api_dir=$(systemctl show --property=WorkingDirectory --value "$api_unit")
[[ $api_dir == /* && $api_dir != "/" ]] || fail 'API servisinin WorkingDirectory değeri bulunamadı.'
api_dir=$(realpath -e -- "$api_dir")
panel_dir=$(realpath -e -- "$panel_input")
api_zip=$(realpath -e -- "$api_zip_input")
panel_zip=$(realpath -e -- "$panel_zip_input")
[[ "$api_dir" != / && "$panel_dir" != / && "$api_dir/" != "$panel_dir/"* &&
   "$panel_dir/" != "$api_dir/"* && "$api_dir/" != */public_html/* ]] || fail 'API ve panel hedef dizinlerini kontrol edin.'
[[ -f "$api_dir/package.json" && -f "$api_dir/lib/index.js" && -r "$api_dir/.env" ]] ||
  fail 'API dizininde package.json, lib/index.js ve mevcut .env dosyası bulunmalı.'
[[ -f "$panel_dir/index.html" ]] || fail 'Panel dizininde mevcut index.html bulunamadı.'
for item in lib migrations assets shared node_modules package.json package-lock.json; do
  [[ ! -L "$api_dir/$item" ]] || fail "Sembolik bağlantı olan API yolu: $api_dir/$item"
done
[[ ! -L "$panel_dir/assets" && ! -L "$panel_dir/index.html" && ! -L "$panel_dir/brand.svg" ]] ||
  fail 'Sembolik bağlantı olan panel yolu bulundu.'
for unit in "${units[@]}"; do
  unit_env=$(systemctl show --property=Environment --value "$unit")
  unit_files=$(systemctl show --property=EnvironmentFiles --value "$unit")
  if [[ $unit_env =~ (^|[[:space:]\"])(DATABASE_|MYSQL_|PRIVATE_STORAGE_PATH=|STORAGE_DIR=) ]]; then
    fail "Servis veritabanı veya depolama ayarlarını .env dışında tanımlıyor: $unit"
  fi
  case "$unit_files" in
    ''|"$api_dir/.env (ignore_errors=no)"|"$api_dir/.env (ignore_errors=yes)") ;;
    *) fail "Servisin farklı bir EnvironmentFile ayarı var: $unit" ;;
  esac
done
unset unit_env unit_files

verify_zip() {
  local sum
  read -r sum _ < <(sha256sum -- "$2")
  [[ $sum == "$1" ]] || fail "ZIP sağlama toplamı eşleşmedi: $2"
}
verify_zip 8e401533fa8100f3318f92e6de65b398836d147cb3221751f7252d0931ffbc93 "$api_zip"
verify_zip 1735346ea3d1645805bd9486e705b83ab6def553305032be472e8c129dbf96ab "$panel_zip"

backup_base="$HOME/.falci-pembe-deploy"
[[ ! -L "$backup_base" ]] || fail 'Yedek dizini sembolik bağlantı.'
mkdir -p -- "$backup_base"
backup_base=$(realpath -e -- "$backup_base")
[[ "$backup_base/" != "$api_dir/"* && "$backup_base/" != "$panel_dir/"* ]] ||
  fail 'Yedek dizini API ve panel dizinlerinin dışında olmalı.'
chmod 700 -- "$backup_base"
backup=$(mktemp -d "$backup_base/release.XXXXXXXX")
mkdir -- "$backup/api-stage" "$backup/panel-stage"
state=prepare
finish() {
  local result=$?
  if (( result != 0 )); then
    if [[ $state == stopped ]]; then
      systemctl start "${units[@]}" || true
    fi
    printf 'Dağıtım durdu. Aşama: %s. Yedek ve hazırlık dizini: %s\n' "$state" "$backup" >&2
    if [[ $state == migration || $state == api-files ]]; then
      printf 'Şema kısmen değişmiş olabilir. Durumu incelemeden migrationu yeniden çalıştırmayın.\n' >&2
    fi
  fi
}
trap finish EXIT

unzip -q "$api_zip" -d "$backup/api-stage"
unzip -q "$panel_zip" -d "$backup/panel-stage"
(
  cd "$backup/api-stage"
  npm ci --omit=dev --no-audit --no-fund
)
db_settings=$(
  cd "$backup/api-stage"
  node - "$api_dir" <<'NODE'
const { readFileSync } = require("node:fs");
const path = require("node:path");
const { parse } = require("dotenv");
const root = process.argv[2];
const env = parse(readFileSync(path.join(root, ".env")));
const host = env.DATABASE_HOST ?? env.MYSQL_HOST ?? "127.0.0.1";
const port = env.DATABASE_PORT ?? env.MYSQL_PORT ?? "3306";
const database = env.DATABASE_NAME ?? env.MYSQL_DATABASE;
const storage = path.resolve(root, env.PRIVATE_STORAGE_PATH ?? env.STORAGE_DIR ?? "private-storage");
if (!["127.0.0.1", "localhost"].includes(host) || port !== "3306" || !/^[a-zA-Z0-9_]+$/.test(database ?? "") || /[\r\n]/.test(storage)) {
  throw new Error("Bu betik yerel MariaDB 3306 ve geçerli bir .env gerektirir.");
}
console.log(database);
console.log(storage);
NODE
)
mapfile -t db_values <<< "$db_settings"
database=${db_values[0]}
storage=${db_values[1]}
[[ "$storage" != / && "$storage" != "$api_dir" && "$storage" != "$panel_dir" ]] ||
  fail 'Özel depolama dizinini kontrol edin.'
[[ -d "$storage" ]] || fail "Özel depolama dizini bulunamadı: $storage"
storage=$(realpath -e -- "$storage")
[[ "$storage" != / && "$storage" != "$api_dir" && "$storage" != "$panel_dir" &&
   "$backup_base/" != "$storage/"* ]] || fail 'Özel depolama dizinini kontrol edin.'
db_client=(mariadb --protocol=socket --batch --skip-column-names --database="$database")
version=$("${db_client[@]}" -e 'SELECT VERSION()')
[[ $version == 10.11.*MariaDB* ]] || fail 'Canlı veritabanı MariaDB 10.11 olmalı.'
applied=$("${db_client[@]}" -e 'SELECT COUNT(*) FROM schema_migrations')
(( applied > 0 )) || fail 'Canlı migration geçmişi boş. Şemayı manuel doğrulayın.'
history=$("${db_client[@]}" -e 'SELECT version,checksum,status FROM schema_migrations')
while IFS=$'\t' read -r filename checksum migration_status; do
  [[ $filename =~ ^[0-9]+[a-zA-Z0-9_.-]*\.sql$ && $migration_status == complete ]] ||
    fail "Geçersiz veya yarım migration: $filename"
  [[ -f "$backup/api-stage/migrations/$filename" ]] ||
    fail "Paket canlıdaki migrationı içermiyor: $filename"
  read -r staged_hash _ < <(sha256sum "$backup/api-stage/migrations/$filename")
  [[ $staged_hash == "$checksum" ]] || fail "Migration sağlama toplamı farklı: $filename"
done <<< "$history"

printf 'API dizini: %s\nPanel dizini: %s\nVeritabanı: %s\nYedek dizini: %s\n' "$api_dir" "$panel_dir" "$database" "$backup"
state=stopped
systemctl stop "${units[@]}"
mariadb-dump --protocol=socket --single-transaction --routines --triggers --events --databases "$database" > "$backup/database.sql"
[[ -s "$backup/database.sql" ]] || fail 'Veritabanı yedeği boş.'
tar -C "$storage" -czf "$backup/private-photos.tgz" .
tar -czf "$backup/api-files.tgz" -C "$api_dir" .
tar -czf "$backup/panel-files.tgz" -C "$panel_dir" .

state=migration
(
  cd "$backup/api-stage"
  env -i PATH="$PATH" HOME="$HOME" NODE_ENV=production DOTENV_CONFIG_PATH="$api_dir/.env" npm run migrate
)
state=api-files
api_owner=$(stat -c '%u:%g' "$api_dir/package.json")
for item in lib migrations assets shared node_modules; do
  [[ ! -L "$api_dir/$item" ]] || fail "Sembolik bağlantı olan dağıtım dizini: $api_dir/$item"
  rsync -a --chown="$api_owner" --chmod=D755,Fgo+r "$backup/api-stage/$item/" "$api_dir/$item/"
done
rsync -a --chown="$api_owner" --chmod=F644 "$backup/api-stage/package.json" "$backup/api-stage/package-lock.json" "$api_dir/"
state=api-health
systemctl start "$api_unit"
healthy=false
for (( attempt=0; attempt<15; attempt++ )); do
  if curl -fsS --max-time 8 https://api.pembe.pink/api/health/ready > /dev/null &&
     curl -fsS --max-time 8 https://api.pembe.pink/api/v1/app-settings |
       node -e 'const v = JSON.parse(require("fs").readFileSync(0,"utf8")); process.exit(typeof v.pembeGreeting === "string" && typeof v.introText === "string" ? 0 : 1)'; then
    healthy=true; break
  fi
  sleep 2
done
[[ $healthy == true ]] || fail 'API sağlık veya uygulama ayarları kontrolü başarısız. Panel henüz yayımlanmadı.'
if [[ $worker_unit != '-' ]]; then systemctl start "$worker_unit"; fi

state=panel
panel_owner=$(stat -c '%u:%g' "$panel_dir/index.html")
[[ ! -L "$panel_dir/assets" && ! -L "$panel_dir/index.html" ]] || fail 'Panel varlık dizini veya index.html sembolik bağlantı.'
rsync -a --chown="$panel_owner" --chmod=D755,Fgo+r "$backup/panel-stage/assets/" "$panel_dir/assets/"
rsync -a --chown="$panel_owner" --chmod=F644 "$backup/panel-stage/brand.svg" "$panel_dir/brand.svg"
if [[ ! -e "$panel_dir/.htaccess" ]]; then
  install -m 644 -o "${panel_owner%:*}" -g "${panel_owner#*:}" "$backup/panel-stage/.htaccess" "$panel_dir/.htaccess"
fi
rsync -a --chown="$panel_owner" --chmod=F644 "$backup/panel-stage/index.html" "$panel_dir/index.html"
asset=$(node -e 'const text = require("fs").readFileSync(process.argv[1], "utf8"); const match = text.match(/src="([^"]+\.js)"/); if (!match) process.exit(1); process.stdout.write(match[1].replace(/^\.\//, "").replace(/^\//, ""));' "$panel_dir/index.html")
curl -fsS --max-time 12 -H 'Cache-Control: no-cache' https://panel.pembe.pink/ > "$backup/panel-health.html"
grep -Fq -- "$asset" "$backup/panel-health.html" || fail 'Canlı panel henüz yeni index dosyasını sunmuyor.'
curl -fsS --max-time 12 "https://panel.pembe.pink/$asset" > "$backup/panel-health.js"
grep -Fq -- '/api/admin/app-settings' "$backup/panel-health.js" || fail 'Canlı panel paketinde yönetim ayarları uç noktası doğrulanamadı.'

state=complete
printf 'Dağıtım tamamlandı. API iki metin alanını ve panel yeni ayar ekranını sunuyor.\nYedek: %s\n' "$backup"

