#!/bin/bash
# ============================================================
# Content Security Service K8s Deploy Script
# Syncs source -> Master node -> builds Docker image ->
# distributes image to Worker nodes via ctr -> applies K8s resources
# -> rolls out the content-security-service deployment.
# ============================================================
set -e

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

SERVICE_DIR="/Users/hanchengxi/workspace/tankwar_proj/content-security-service"
DEPLOY_DIR="/Users/hanchengxi/workspace/tankwar_proj/deploy/content-security"
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/content-security-build"
IMAGE_NAME="content-security-service:latest"

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

# ------------------------------------------------------------
# Step 0: Sync service source to master node
# ------------------------------------------------------------
echo "$(ts) ===== Syncing content-security-service source to master node ====="
ssh -o StrictHostKeyChecking=no "$MASTER" "mkdir -p $REMOTE_BUILD_DIR"
rsync -az --delete --exclude='.git' --exclude='node_modules' \
    -e "ssh -o StrictHostKeyChecking=no" \
    "$SERVICE_DIR/" "${MASTER}:${REMOTE_BUILD_DIR}/"
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 && 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
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
# ------------------------------------------------------------
echo "$(ts) ===== Applying K8s manifests ====="
# Apply in order: namespace first, then configmap/secret, then deployment/service
for manifest in namespace.yaml configmap.yaml secret.yaml deployment.yaml service.yaml networkpolicy.yaml; do
    if [ -f "$DEPLOY_DIR/$manifest" ]; then
        echo "$(ts)   Applying $manifest"
        cat "$DEPLOY_DIR/$manifest" | \
            ssh -o StrictHostKeyChecking=no "$MASTER" "kubectl apply -f -"
    fi
done
echo "$(ts) ✓ Manifests applied"

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

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

echo ""
echo "$(ts) ===== ALL DONE ====="
echo "$(ts) Internal endpoint: content-security-service.content-security.svc.cluster.local:3000"
echo "$(ts) Game services should call: http://content-security-service.content-security.svc.cluster.local:3000/api/content/..."

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