#!/usr/bin/env bash
# Foodlinkk Command Center — volledige deploy (migraties + build + health)
set -euo pipefail

PASS="${FOODLINKK_SSH_PASS:-Foodlinkk#2026}"
VM="${FOODLINKK_VM:-aissa@10.4.7.18}"
REMOTE_DIR="${FOODLINKK_REMOTE_DIR:-/home/aissa/foodlinkk-command-center}"
LOCAL_DIR="$(cd "$(dirname "$0")" && pwd)"

echo "=== Foodlinkk deploy-all ==="
echo "Local:  $LOCAL_DIR"
echo "Remote: $VM:$REMOTE_DIR"

if ! command -v sshpass >/dev/null 2>&1; then
  echo "sshpass is vereist (apt install sshpass)"
  exit 1
fi

echo "=== Rsync naar VM106 ==="
sshpass -p "$PASS" rsync -az --delete \
  --exclude '.git' \
  --exclude '__pycache__' \
  --exclude '*.pyc' \
  --exclude '.env' \
  --exclude 'node_modules' \
  -e "ssh -o StrictHostKeyChecking=no" \
  "$LOCAL_DIR/" "$VM:$REMOTE_DIR/"

echo "=== Migraties + Docker rebuild op VM106 ==="
sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$VM" bash -s <<REMOTE
set -euo pipefail
cd "$REMOTE_DIR"

for mig in migrations/*.sql; do
  echo "Applying \$(basename "\$mig")..."
  docker exec -i foodlinkk_db psql -U aissa -d foodlinkk < "\$mig" || true
done

docker compose build tools-api cockpit email-agent browser-agent
docker compose up -d

echo "Waiting for services..."
sleep 15

curl -sf http://127.0.0.1:8700/health && echo " tools-api OK" || echo " tools-api FAIL"
curl -sf -o /dev/null -w "cockpit:%{http_code}\n" http://127.0.0.1:8600/
curl -sf -o /dev/null -w "marketing:%{http_code}\n" http://127.0.0.1:8600/marketing
curl -sf -o /dev/null -w "ops:%{http_code}\n" http://127.0.0.1:8600/ops
curl -sf -o /dev/null -w "packaging:%{http_code}\n" http://127.0.0.1:8600/packaging
curl -sf -o /dev/null -w "agents:%{http_code}\n" http://127.0.0.1:8600/agents

echo "=== SysOps daily cron (07:00) ==="
(crontab -l 2>/dev/null | grep -v sysops_daily.py; echo "0 7 * * * cd $REMOTE_DIR && /usr/bin/python3 scripts/sysops_daily.py >> /tmp/sysops-daily.log 2>&1") | crontab -
echo "Cron installed"

echo "=== Run SysOps daily now (test) ==="
cd "$REMOTE_DIR" && python3 scripts/sysops_daily.py || true
REMOTE

echo "=== Deploy voltooid ==="
echo "Cockpit:  http://10.4.7.18:8600"
echo "Tools API: http://10.4.7.18:8700"
echo "Gitea:    http://10.4.7.18:3001"
