#!/bin/bash
# Deploy web push notification feature to portal
# Run: sudo bash /var/www/html/portal/scripts/deploy-push-notifications.sh

set -e

PORTAL=/var/www/html/portal
VPN=/var/www/html/vpn

echo "=== Deploying Web Push Notifications to Portal ==="

# ── 1. Migrations ────────────────────────────────────────────
echo "[1] Copying migrations..."
for f in \
    2026_05_18_172233_create_notifications_tables.php \
    2026_05_18_172233_create_push_subscriptions_table.php; do
    if [ ! -f "$PORTAL/database/migrations/$f" ]; then
        cp "$VPN/database/migrations/$f" "$PORTAL/database/migrations/$f"
        chown www-data:www-data "$PORTAL/database/migrations/$f"
        echo "  copied $f"
    else
        echo "  skip (exists): $f"
    fi
done

# ── 2. Service Worker ────────────────────────────────────────
echo "[2] Writing sw.js..."
cat > "$PORTAL/public/sw.js" << 'SWEOF'
const CACHE_NAME = 'portal-v1';

self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (e) => {
  e.waitUntil(
    caches.keys().then(keys =>
      Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k)))
    )
  );
  self.clients.claim();
});

self.addEventListener('push', (event) => {
  if (!event.data) return;
  const data = event.data.json();
  event.waitUntil(
    self.registration.showNotification(data.title || '管理後臺', {
      body:    data.body  || '',
      icon:    data.icon  || '/icon-192x192.png',
      badge:   '/icon-96x96.png',
      data:    { url: data.url || '/' },
      vibrate: [200, 100, 200],
    })
  );
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const url = event.notification.data?.url || '/';
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then(list => {
      for (const c of list) {
        if (c.url.includes(self.location.origin) && 'focus' in c) {
          c.navigate(url);
          return c.focus();
        }
      }
      return clients.openWindow(url);
    })
  );
});
SWEOF
chown www-data:www-data "$PORTAL/public/sw.js"
echo "  sw.js written"

# ── 3. VAPID config in services.php ─────────────────────────
echo "[3] Adding VAPID to services.php..."
if ! grep -q 'vapid' "$PORTAL/config/services.php"; then
    # Insert before last closing bracket
    sed -i "s/];$/\n    'vapid' => [\n        'public_key'  => env('VAPID_PUBLIC_KEY'),\n        'private_key' => env('VAPID_PRIVATE_KEY'),\n    ],\n\n];/" "$PORTAL/config/services.php"
    echo "  VAPID config added"
else
    echo "  skip (already present)"
fi

# ── 4. VAPID keys in .env ────────────────────────────────────
echo "[4] Adding VAPID keys to .env..."
if ! grep -q 'VAPID_PUBLIC_KEY' "$PORTAL/.env"; then
    VPN_PUB=$(grep 'VAPID_PUBLIC_KEY=' "$VPN/.env" | cut -d= -f2-)
    VPN_PRIV=$(grep 'VAPID_PRIVATE_KEY=' "$VPN/.env" | cut -d= -f2-)
    echo "" >> "$PORTAL/.env"
    echo "# Web Push (VAPID)" >> "$PORTAL/.env"
    echo "VAPID_PUBLIC_KEY=${VPN_PUB}" >> "$PORTAL/.env"
    echo "VAPID_PRIVATE_KEY=${VPN_PRIV}" >> "$PORTAL/.env"
    echo "  VAPID keys added (same as vpn)"
else
    echo "  skip (already present)"
fi

# ── 5. Composer install ──────────────────────────────────────
echo "[5] Installing minishlink/web-push..."
cd "$PORTAL"
if ! grep -q 'minishlink/web-push' composer.json; then
    sudo -u www-data composer require minishlink/web-push:^10.0 --no-interaction
    echo "  package installed"
else
    echo "  skip (already in composer.json)"
fi

# ── 6. Run migrations ────────────────────────────────────────
echo "[6] Running migrations..."
sudo -u www-data php artisan migrate --force --no-interaction
echo "  migrations done"

# ── 7. Clear config cache ────────────────────────────────────
echo "[7] Clearing cache..."
sudo -u www-data php artisan config:clear
sudo -u www-data php artisan route:clear
echo "  cache cleared"

echo ""
echo "=== Done! Web push notifications deployed to portal ==="
