#!/usr/bin/env bash
# One-time prod preparation for KORZILLA.Admin deploys. Safe to re-run (each step checks its state).
#  - backend checkout: origin GitLab -> GitHub (GitLab kept as remote "gitlab",
#    its ddd/new-arch branches pinned as local branches gitlab-ddd/gitlab-new-arch)
#  - frontend: clone from GitHub next to the backend + .env with the values of the running container
#  - deploy scripts: installed to /root/deploy/korzilla-admin
# Does NOT build, restart or touch the database.
# Usage (as root): bash prepare-server.sh
set -Eeuo pipefail

APPS=/home/adminapp/web/admin.korzilla.ru/apps
BACKEND=$APPS/backend
FRONTEND=$APPS/frontend
DEPLOY_DIR=/root/deploy/korzilla-admin
SRC_DIR=$(cd "$(dirname "$0")" && pwd)

log() { printf '\n[%s] %s\n' "$(date +%H:%M:%S)" "$*"; }

log "Backend: switch origin to GitHub"
cd "$BACKEND"
if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
  git status --short
  echo "Backend has uncommitted changes, aborting" >&2
  exit 1
fi
if git remote get-url origin | grep -q gitlab.com; then
  git remote rename origin gitlab
fi
for b in ddd new-arch; do
  if git rev-parse -q --verify "refs/remotes/gitlab/$b" >/dev/null && ! git rev-parse -q --verify "refs/heads/gitlab-$b" >/dev/null; then
    git branch "gitlab-$b" "gitlab/$b"
  fi
done
if ! git remote get-url origin >/dev/null 2>&1; then
  git remote add origin git@github-korzilla-admin-backend:korzilla-ru/korzilla-admin-backend.git
fi
git fetch -q origin </dev/null
git branch -q --set-upstream-to=origin/main main
git remote -v | sed -E 's#//[^@/]+@#//***@#'
echo "HEAD $(git rev-parse --short HEAD); behind origin/main: $(git rev-list --count HEAD..origin/main)"

log "Frontend: clone"
if [ ! -d "$FRONTEND/.git" ]; then
  git clone -q git@github-korzilla-admin-frontend:korzilla-ru/korzilla-admin-frontend.git "$FRONTEND" </dev/null
fi
if [ ! -f "$FRONTEND/.env" ]; then
  # Same values as the running "frontend" container
  cat > "$FRONTEND/.env" <<'ENV'
NEXT_PUBLIC_URL=https://admin.korzilla.ru
NEXT_PUBLIC_API_URL=https://admin.korzilla.ru/api
ENV
  chmod 600 "$FRONTEND/.env"
fi
echo "frontend HEAD $(git -C "$FRONTEND" rev-parse --short HEAD)"

log "Install deploy scripts to $DEPLOY_DIR"
mkdir -p "$DEPLOY_DIR"
install -m 700 "$SRC_DIR/deploy-backend.sh" "$SRC_DIR/deploy-frontend.sh" "$DEPLOY_DIR/"
ls -la "$DEPLOY_DIR"

log "Done"
