#!/bin/bash
# Deploy taawunu-site to production
# Usage: ./deploy.sh
set -euo pipefail

REMOTE="root@159.195.60.33"
KEY="$HOME/.ssh/id_ed25519"
CONTAINER="qc-server-new"

echo "→ Pushing to Gitea..."
git push origin main 2>&1

echo "→ Pulling on server..."
ssh -i "$KEY" "$REMOTE" "incus exec $CONTAINER -- bash -c 'cd /opt/taawunu-site && git pull origin main 2>&1'"

echo "→ Building Docker image..."
ssh -i "$KEY" "$REMOTE" "incus exec $CONTAINER -- bash -c 'cd /opt/taawunu-site && docker build -t taawunu-site:latest . 2>&1 | tail -3'"

echo "→ Updating service..."
ssh -i "$KEY" "$REMOTE" "incus exec $CONTAINER -- bash -c 'docker service update --force --image taawunu-site:latest taawunu-site 2>&1 | tail -3'"

echo "→ Health check..."
sleep 3
STATUS=$(ssh -i "$KEY" "$REMOTE" "incus exec $CONTAINER -- curl -sk -o /dev/null -w '%{http_code}' -H 'Host: taawunu.quikcue.com' https://localhost:443/ 2>&1")
if [ "$STATUS" = "200" ]; then
  echo "✓ Deployed successfully! Status: $STATUS"
else
  echo "✗ Health check returned: $STATUS"
  exit 1
fi
