#!/bin/bash
# ============================================================
# Tankwar server K8s deploy script
# Syncs server source -> Master node -> builds Docker image ->
# distributes image to Worker nodes via ctr -> applies K8s resources
# -> rolls out the tankwar-server deployment.
# ============================================================
set -e

LOG="/tmp/tankwar-k8s-deploy.log"
> "$LOG"
exec > >(tee -a "$LOG") 2>&1

SERVER_DIR="/Users/hanchengxi/workspace/tankwar_proj/server"
MASTER="root@host_172.16.16.16"
WORKERS_IP=("10.1.0.6" "172.16.32.10" "172.16.32.16")
REMOTE_BUILD_DIR="/tmp/tankwar-build"
IMAGE_NAME="tankwar/tankwar-server:latest"

ts() { echo "[$(date '+%H:%M:%S')]"; }

# ------------------------------------------------------------
# Step 0: Sync server source to master node
# ------------------------------------------------------------
echo "$(ts) ===== Syncing tankwar server source to master node ====="
ssh -o StrictHostKeyChecking=no "$MASTER" "mkdir -p $REMOTE_BUILD_DIR"
rsync -az --delete --exclude='.git' \
    -e "ssh -o StrictHostKeyChecking=no" \
    "$SERVER_DIR/" "${MASTER}:${REMOTE_BUILD_DIR}/server/"
echo "$(ts) ✓ Source synced"

# ------------------------------------------------------------
# Step 1: Ensure docker is available on master
# ------------------------------------------------------------
echo "$(ts) ===== Checking docker on master ====="
if ! ssh -o StrictHostKeyChecking=no "$MASTER" "which docker >/dev/null 2>&1"; then
    echo "$(ts) Docker not found on master. Installing..."
    ssh -o StrictHostKeyChecking=no "$MASTER" "curl -fsSL https://get.docker.com | sh"
fi
ssh -o StrictHostKeyChecking=no "$MASTER" "docker version --format '{{.Server.Version}}' 2>/dev/null || systemctl start docker"
echo "$(ts) ✓ Docker ready on master"

# ------------------------------------------------------------
# Step 2: Build image on master
# ------------------------------------------------------------
echo "$(ts) ===== Building $IMAGE_NAME on master ====="
ssh -o StrictHostKeyChecking=no "$MASTER" \
    "cd $REMOTE_BUILD_DIR/server && docker build -t $IMAGE_NAME -f Dockerfile ."
echo "$(ts) ✓ Image built"

# ------------------------------------------------------------
# Step 3: Distribute image to workers (containerd / ctr)
# ------------------------------------------------------------
echo "$(ts) ===== Distributing $IMAGE_NAME to workers ====="
# Master itself may also be a worker; import locally first so master pods can use it.
ssh -o StrictHostKeyChecking=no "$MASTER" \
    "docker save $IMAGE_NAME | ctr -n k8s.io images import -"
for w in "${WORKERS_IP[@]}"; do
    echo "$(ts)   -> $w"
    ssh -o StrictHostKeyChecking=no "$MASTER" \
        "docker save $IMAGE_NAME | ssh -o StrictHostKeyChecking=no root@$w 'ctr -n k8s.io images import -'"
done
echo "$(ts) ✓ Image distributed"

# ------------------------------------------------------------
# Step 4: Apply K8s manifests (namespace + configmap + deploy + svc)
# ------------------------------------------------------------
echo "$(ts) ===== Applying K8s manifests ====="
cat "$SERVER_DIR/k8s-deployment.yaml" | \
    ssh -o StrictHostKeyChecking=no "$MASTER" "kubectl apply -f -"
echo "$(ts) ✓ Manifests applied"

# ------------------------------------------------------------
# Step 5: Restart deployment to pick up the new image
# ------------------------------------------------------------
echo "$(ts) ===== Restarting tankwar-server deployment ====="
ssh -o StrictHostKeyChecking=no "$MASTER" \
    "kubectl -n tankwar rollout restart deployment/tankwar-server" || true
ssh -o StrictHostKeyChecking=no "$MASTER" \
    "kubectl -n tankwar rollout status deployment/tankwar-server --timeout=120s" || true

# ------------------------------------------------------------
# Step 6: Show final status
# ------------------------------------------------------------
echo "$(ts) ===== Final Status ====="
ssh -o StrictHostKeyChecking=no "$MASTER" "kubectl -n tankwar get pods -o wide"
echo ""
ssh -o StrictHostKeyChecking=no "$MASTER" "kubectl -n tankwar get svc"

echo ""
echo "$(ts) ===== ALL DONE ====="
echo "$(ts) Public endpoint (via warmcheck Nginx): wss://www.igeek.site/games/wx/tankwar/ws"
echo "$(ts) Internal endpoint: tankwar-server.tankwar.svc.cluster.local:3000"
echo "$(ts) Remember to redeploy warmcheck Nginx too (run WarmCheck_proj/backend/deploy/k8s/scripts/run-deploy.sh)"

# Cleanup
ssh -o StrictHostKeyChecking=no "$MASTER" "rm -rf $REMOTE_BUILD_DIR" 2>/dev/null || true
