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

TEST_HOST="${TEST_HOST:-player@93.170.12.154}"
TARGET_DOMAIN="${TARGET_DOMAIN:-test.shineup.me}"
REMOTE_UI_DIR="${REMOTE_UI_DIR:-/home/player/SHiNE/shine-ui}"
REMOTE_CADDYFILE="${REMOTE_CADDYFILE:-/etc/caddy/Caddyfile}"

TMP_DIR="$(mktemp -d)"

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

cat >"$TMP_DIR/Caddyfile" <<EOF
{
	auto_https disable_redirects
}

$TARGET_DOMAIN {
	encode zstd gzip

	@ws path /ws /ws/*
	handle @ws {
		reverse_proxy 127.0.0.1:7070
	}

	handle {
		root * $REMOTE_UI_DIR
		try_files {path} /index.html
		file_server
		header -Etag
		header {
			Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
			Pragma "no-cache"
			Expires "0"
		}
	}
}

:80 {
	encode zstd gzip

	@ws path /ws /ws/*
	handle @ws {
		reverse_proxy 127.0.0.1:7070
	}

	handle {
		root * $REMOTE_UI_DIR
		try_files {path} /index.html
		file_server
		header -Etag
		header {
			Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
			Pragma "no-cache"
			Expires "0"
		}
	}
}
EOF

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

echo "==> Установка Caddy-конфига для $TARGET_DOMAIN"
scp -p "$TMP_DIR/Caddyfile" "$TEST_HOST:/tmp/shine-test-caddyfile.new" >/dev/null
ssh "$TEST_HOST" "sudo mkdir -p \"$(dirname "$REMOTE_CADDYFILE")\" && \
  sudo mv -f /tmp/shine-test-caddyfile.new \"$REMOTE_CADDYFILE\" && \
  sudo chown root:root \"$REMOTE_CADDYFILE\" && \
  sudo caddy validate --config \"$REMOTE_CADDYFILE\" && \
  sudo systemctl reload caddy"

echo "==> Caddy настроен для $TARGET_DOMAIN"
