#!/usr/bin/env bash
set -euo pipefail

PROD_HOST="${PROD_HOST:-player@shineup.me}"
TEST_HOST="${TEST_HOST:-player@93.170.12.154}"
TARGET_DOMAIN="${TARGET_DOMAIN:-test.shineup.me}"
REMOTE_BASE="${REMOTE_BASE:-/home/player/SHiNE}"
REMOTE_SERVER_DIR="${REMOTE_SERVER_DIR:-$REMOTE_BASE/shine-server}"
REMOTE_UI_DIR="${REMOTE_UI_DIR:-$REMOTE_BASE/shine-ui}"
REMOTE_DATA_DIR="${REMOTE_DATA_DIR:-$REMOTE_SERVER_DIR/data}"
REMOTE_LOGS_DIR="${REMOTE_LOGS_DIR:-$REMOTE_SERVER_DIR/logs}"
REMOTE_SERVICE_NAME="${REMOTE_SERVICE_NAME:-shine-server}"
LOCAL_JAR="${LOCAL_JAR:-build/libs/shine-server.jar}"
PROD_DATA_DIR="${PROD_DATA_DIR:-/home/player/SHiNE/shine-server/data}"
PROD_APP_PROPS="${PROD_APP_PROPS:-/home/player/SHiNE/shine-server/application.properties}"

TMP_DIR="$(mktemp -d)"

cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

require_file() {
  local path="$1"
  if [[ ! -f "$path" ]]; then
    echo "ERROR: файл не найден: $path" >&2
    exit 1
  fi
}

echo "==> Проверка локального jar"
require_file "$LOCAL_JAR"
jar_size="$(stat -c %s "$LOCAL_JAR")"
if [[ "$jar_size" -lt 10485760 ]]; then
  echo "ERROR: jar слишком маленький для fat-jar: $jar_size bytes" >&2
  exit 1
fi

echo "==> Проверка SSH и sudo"
ssh -o BatchMode=yes -o ConnectTimeout=10 "$PROD_HOST" "echo SSH OK" >/dev/null
ssh -o BatchMode=yes -o ConnectTimeout=10 "$TEST_HOST" "echo SSH OK" >/dev/null
ssh "$TEST_HOST" "sudo -n true"

echo "==> Подготовка Caddy для $TARGET_DOMAIN"
TEST_HOST="$TEST_HOST" \
TARGET_DOMAIN="$TARGET_DOMAIN" \
REMOTE_UI_DIR="$REMOTE_UI_DIR" \
bash "$(dirname "$0")/scripts/install_test_caddyfile.sh"

echo "==> Забираем продовые данные и application.properties"
mkdir -p "$TMP_DIR/data"
rsync -az --delete "$PROD_HOST:$PROD_DATA_DIR/" "$TMP_DIR/data/"
scp -p "$PROD_HOST:$PROD_APP_PROPS" "$TMP_DIR/application.properties" >/dev/null

if grep -q '^server\.ui\.indexPath=' "$TMP_DIR/application.properties"; then
  perl -0pi -e 's@^server\.ui\.indexPath=.*$@server.ui.indexPath=/home/player/SHiNE/shine-ui/index.html@m' "$TMP_DIR/application.properties"
else
  printf '\nserver.ui.indexPath=/home/player/SHiNE/shine-ui/index.html\n' >>"$TMP_DIR/application.properties"
fi

cat >"$TMP_DIR/shine-server.service" <<EOF
[Unit]
Description=SHiNE Server
After=network.target

[Service]
Type=simple
User=player
Group=player
WorkingDirectory=$REMOTE_SERVER_DIR
ExecStart=/usr/bin/java -Dserver.port=7070 -jar $REMOTE_SERVER_DIR/shine-server.jar
Restart=always
RestartSec=3
StandardOutput=append:$REMOTE_LOGS_DIR/app.log
StandardError=append:$REMOTE_LOGS_DIR/app.log

[Install]
WantedBy=multi-user.target
EOF

echo "==> Останавливаем текущий сервер на тестовом хосте"
ssh "$TEST_HOST" "sudo systemctl stop $REMOTE_SERVICE_NAME || true"

echo "==> Создаём каталоги"
ssh "$TEST_HOST" "mkdir -p '$REMOTE_SERVER_DIR' '$REMOTE_DATA_DIR' '$REMOTE_LOGS_DIR' '$REMOTE_UI_DIR' '$REMOTE_BASE/caddy'"

echo "==> Копируем продовую БД и blockchain-данные"
rsync -az --delete "$TMP_DIR/data/" "$TEST_HOST:$REMOTE_DATA_DIR/"

echo "==> Загружаем новый jar и конфиг"
rsync -az --timeout=120 "$LOCAL_JAR" "$TEST_HOST:$REMOTE_SERVER_DIR/shine-server.jar.new"
rsync -az --timeout=30 "$TMP_DIR/application.properties" "$TEST_HOST:$REMOTE_SERVER_DIR/application.properties.new"
rsync -az --timeout=30 "$TMP_DIR/shine-server.service" "$TEST_HOST:/tmp/shine-server.service.new"

echo "==> Применяем systemd unit и файлы сервера"
ssh "$TEST_HOST" "set -euo pipefail; \
  mv -f '$REMOTE_SERVER_DIR/shine-server.jar.new' '$REMOTE_SERVER_DIR/shine-server.jar'; \
  mv -f '$REMOTE_SERVER_DIR/application.properties.new' '$REMOTE_SERVER_DIR/application.properties'; \
  sudo mv -f /tmp/shine-server.service.new /etc/systemd/system/shine-server.service; \
  sudo chown root:root /etc/systemd/system/shine-server.service; \
  chmod 644 '$REMOTE_SERVER_DIR/application.properties'; \
  chmod 664 '$REMOTE_SERVER_DIR/shine-server.jar'; \
  mkdir -p '$REMOTE_LOGS_DIR'; \
  sudo chown -R player:player '$REMOTE_SERVER_DIR'; \
  touch '$REMOTE_LOGS_DIR/app.log'; \
  sudo systemctl daemon-reload; \
  sudo systemctl enable '$REMOTE_SERVICE_NAME'; \
  sudo systemctl restart '$REMOTE_SERVICE_NAME'"

echo "==> Ждём порт 7070"
for _ in $(seq 1 50); do
  if ssh "$TEST_HOST" "ss -ltn '( sport = :7070 )' | grep -q 7070"; then
    echo "==> Порт 7070 поднялся"
    break
  fi
  sleep 1
done

if ! ssh "$TEST_HOST" "ss -ltn '( sport = :7070 )' | grep -q 7070"; then
  echo "ERROR: тестовый сервер не поднял порт 7070" >&2
  exit 1
fi

echo "==> Проверяем статус сервиса"
ssh "$TEST_HOST" "sudo systemctl --no-pager --full status '$REMOTE_SERVICE_NAME' | sed -n '1,20p'"

echo "test_server_deploy_done"
