#!/bin/bash
# Deploy/update scripter.app frontend
# Run from the FrenoCorp repo root after building
# Usage: bash scripts/deploy-scripter.sh

set -e

echo "=== Deploying scripter.app ==="

# 1. Build (if needed)
if [ "$1" != "--skip-build" ]; then
  echo "[1/4] Building frontend..."
  npm run build
else
  echo "[1/4] Skipping build (--skip-build)"
fi

# 2. Copy to web directory
echo "[2/4] Copying to web directory..."
docker run --rm \
  -v /home/mike/code/FrenoCorp/dist:/dist:ro \
  -v /var/www/scripter:/target \
  alpine sh -c "cp -r /dist/* /target/ && chmod -R 755 /target/"
echo "  Copied $(find /var/www/scripter -type f | wc -l) files"

# 3. Reload nginx
echo "[3/4] Reloading nginx..."
if docker run --rm --pid=host --privileged alpine sh -c "kill -HUP 1280" 2>&1; then
  echo "  Nginx reloaded"
else
  echo "  WARNING: Could not reload nginx (try manually: sudo systemctl reload nginx)"
fi

# 4. Verify
echo "[4/4] Verifying..."
sleep 1
HTTP_CODE=$(curl -sk -o /dev/null -w "%{http_code}" https://scripter.app/ --resolve scripter.app:443:66.108.41.120 2>/dev/null || echo "failed")
if [ "$HTTP_CODE" = "200" ]; then
  echo "  ✅ Site is serving HTTP 200"
else
  echo "  ❌ Site returned HTTP $HTTP_CODE"
fi

echo ""
echo "=== Deploy complete ==="
echo "Verify at: curl -skI https://scripter.app/ --resolve scripter.app:443:66.108.41.120"
