#!/usr/bin/env bash

set -u

BASE="/opt/digidala"
RELEASES="$BASE/releases"
CURRENT="$BASE/current"
WEB_SERVICE="digidala-production-web"
API_SERVICE="digidala-production-api"
BOT_SERVICE="digidala-production-bot"
HEALTH_URL="${DIGIDALA_HEALTH_URL:-https://digidala.ru/apps/miniapp/index.html}"
TAG="${1:-}"

if [[ -z "$TAG" ]]; then
  echo "Использование: $0 <tag>"
  exit 1
fi

TARGET="$RELEASES/$TAG"
if [[ ! -d "$TARGET" ]]; then
  echo "Ошибка: production release не найден: $TARGET"
  exit 1
fi

for service in "$WEB_SERVICE" "$API_SERVICE" "$BOT_SERVICE"; do
  if [[ ! -f "$TARGET/infra/systemd/${service}.service" ]]; then
    echo "Ошибка: release не содержит $service.service"
    exit 1
  fi
done

echo "==> Переключаю DigiDala production на $TAG..."
TMP_LINK="$BASE/.current-new"
rm -f "$TMP_LINK"
ln -s "$TARGET" "$TMP_LINK"
mv -Tf "$TMP_LINK" "$CURRENT"

for service in "$WEB_SERVICE" "$API_SERVICE" "$BOT_SERVICE"; do
  sudo install -m 0644 "$TARGET/infra/systemd/${service}.service" "/etc/systemd/system/${service}.service" || exit 1
done

sudo systemctl daemon-reload || exit 1
sudo systemctl restart "$WEB_SERVICE" "$API_SERVICE" "$BOT_SERVICE" || exit 1
sleep 2

if ! sudo systemctl is-active --quiet "$WEB_SERVICE" || \
   ! sudo systemctl is-active --quiet "$API_SERVICE" || \
   ! sudo systemctl is-active --quiet "$BOT_SERVICE"; then
  echo "Ошибка: production service не запустились."
  exit 1
fi

if ! curl -fsSI "$HEALTH_URL" >/dev/null; then
  echo "Ошибка: production smoke test не пройден."
  exit 1
fi

echo
echo "========================================"
echo " DIGIDALA PRODUCTION ROLLBACK УСПЕШНО ВЫПОЛНЕН"
echo " Версия: $TAG"
echo " Current: $(readlink -f "$CURRENT")"
echo "========================================"
