#!/bin/bash
# Deploy script for k3s cluster
# Run this on the k3s master node after pulling latest code

set -e

NAMESPACE="student-enrollment"
PROJECT_DIR="/home/andres/student-enrollment"
TAG=$(git -C "$PROJECT_DIR" rev-parse --short HEAD)

echo "=== Deploying commit $TAG to k3s ==="

cd "$PROJECT_DIR"
git pull

echo "=== Building API image ==="
sudo docker build -t student-api:$TAG -f deploy/docker/Dockerfile.api .

echo "=== Building Frontend image ==="
sudo docker build -t student-frontend:$TAG -f deploy/docker/Dockerfile.frontend .

echo "=== Importing images to k3s ==="
sudo docker save student-api:$TAG | sudo k3s ctr images import -
sudo docker save student-frontend:$TAG | sudo k3s ctr images import -

echo "=== Updating deployments ==="
sudo kubectl -n $NAMESPACE set image deployment/student-api api=student-api:$TAG
sudo kubectl -n $NAMESPACE set image deployment/student-frontend frontend=student-frontend:$TAG

echo "=== Waiting for rollout ==="
sudo kubectl -n $NAMESPACE rollout status deployment/student-api --timeout=120s
sudo kubectl -n $NAMESPACE rollout status deployment/student-frontend --timeout=60s

echo "=== Health check ==="
sleep 5
API_POD=$(sudo kubectl -n $NAMESPACE get pods -l app=student-api -o jsonpath='{.items[0].metadata.name}')
sudo kubectl -n $NAMESPACE exec $API_POD -- wget -q --spider http://localhost:5000/health

echo "=== Deploy complete! Tag: $TAG ==="
