#!/usr/bin/env bash
# Deploys the KORZILLA.Admin frontend on prod (Docker container "frontend"):
#   checks -> checkout -> keep current image as :rollback -> docker compose up --build -> health check.
# If the build or the health check fails, the code and the container are rolled back to the
# previous image.
#
# Usage (as root):
#   deploy-frontend.sh                 deploy origin/main
#   deploy-frontend.sh <git-ref>       deploy a branch/tag/commit (detached HEAD)
#   DRY_RUN=1 deploy-frontend.sh       show what would be deployed, change nothing
#   FORCE=1 deploy-frontend.sh         rebuild even if already on the target commit
set -Eeuo pipefail

APP=/home/adminapp/web/admin.korzilla.ru/apps/frontend
# Same compose project as the container originally started by the GitLab runner, so compose
# recreates that container instead of clashing with its name.
PROJECT=korzilla-admin-frontend
IMAGE=korzilla-admin-frontend-frontend
CONTAINER=frontend
HEALTH_URLS="http://127.0.0.1:3000/ http://127.0.0.1:3000/auth/signin"
MIN_FREE_GB=4

REF=${1:-origin/main}
DRY_RUN=${DRY_RUN:-0}
FORCE=${FORCE:-0}

log() { printf '\n[%s] %s\n' "$(date +%H:%M:%S)" "$*"; }
die() { echo "ERROR: $*" >&2; exit 1; }
compose() { docker compose -p "$PROJECT" "$@"; }

exec 9>/var/lock/korzilla-admin-frontend-deploy.lock
flock -n 9 || die "another frontend deploy is running"

cd "$APP"

log "Checks"
[ -z "$(git status --porcelain --untracked-files=no)" ] || { git status --short; die "uncommitted changes in $APP"; }
[ -f .env ] || die ".env missing in $APP (NEXT_PUBLIC_* are baked in at build time)"
free_gb=$(df -BG --output=avail / | tail -1 | tr -dc 0-9)
[ "$free_gb" -ge "$MIN_FREE_GB" ] || die "only ${free_gb}G free on /, need ${MIN_FREE_GB}G for the docker build"
echo "free on /: ${free_gb}G"

git fetch -q origin </dev/null
PREV=$(git rev-parse HEAD)
NEXT=$(git rev-parse "$REF^{commit}")
echo "checkout current: $(git log -1 --format='%h %ad %s' --date=short "$PREV")"
echo "target:           $(git log -1 --format='%h %ad %s' --date=short "$NEXT")  ($REF)"
echo "running container: $(docker inspect "$CONTAINER" --format '{{.Config.Image}} created {{.Created}} {{.State.Status}}' 2>/dev/null || echo none)"
if [ "$PREV" = "$NEXT" ] && [ "$FORCE" != 1 ]; then
  echo "Already on target, nothing to deploy (FORCE=1 to rebuild)"
  exit 0
fi
echo "--- commits:"; git log --oneline "$PREV..$NEXT"
echo "--- changed files:"; git diff --stat "$PREV" "$NEXT" | tail -30

if [ "$DRY_RUN" = 1 ]; then
  log "DRY_RUN: nothing changed"
  exit 0
fi

ROLLBACK_ARMED=0
HAVE_ROLLBACK_IMAGE=0
rollback() {
  [ "$ROLLBACK_ARMED" = 1 ] || return 0
  ROLLBACK_ARMED=0
  set +e
  log "ROLLBACK to $(git rev-parse --short "$PREV")"
  git checkout -q --detach "$PREV"
  if [ "$HAVE_ROLLBACK_IMAGE" = 1 ]; then
    docker tag "$IMAGE:rollback" "$IMAGE:latest"
    compose up -d --no-build --force-recreate
    echo "Container restored from $IMAGE:rollback"
  else
    echo "No previous image to restore, check the container manually"
  fi
}
# EXIT (not ERR) so that explicit `die` after checkout also rolls back
trap 'rc=$?; if [ "$rc" -ne 0 ]; then echo "FAILED (exit $rc)" >&2; rollback; fi' EXIT

log "Checkout"
ROLLBACK_ARMED=1
if [ "$REF" = origin/main ]; then
  git checkout -q main
  git merge -q --ff-only origin/main
else
  git checkout -q --detach "$NEXT"
fi
echo "HEAD: $(git log -1 --format='%h %s')"

log "Build and recreate container"
if docker image inspect "$IMAGE:latest" >/dev/null 2>&1; then
  docker tag "$IMAGE:latest" "$IMAGE:rollback"
  HAVE_ROLLBACK_IMAGE=1
  echo "previous image saved as $IMAGE:rollback"
fi
compose build
compose up -d --no-build

log "Health check"
for url in $HEALTH_URLS; do
  code=000
  for _ in $(seq 1 30); do
    sleep 2
    code=$(curl -s -o /dev/null -w '%{http_code}' "$url" || true)
    [ "$code" = 200 ] && break
  done
  echo "$url -> $code"
  if [ "$code" != 200 ]; then
    docker logs --tail 40 "$CONTAINER" 2>&1 | cut -c1-240
    die "health check failed: $url -> $code"
  fi
done
ROLLBACK_ARMED=0

log "Cleanup dangling images"
docker image prune -f | tail -1

log "OK: frontend $(git log -1 --format='%h %s') is up"
echo "rollback image kept: $IMAGE:rollback"
