#!/usr/bin/env bash
#
# start.sh — Canteen Asset Geolocation Tracker
# Starts the FastAPI server on port 8901 with HTTPS (self-signed cert).
#

set -euo pipefail

PROJECT_DIR="$(cd "$(dirname "$0")" && pwd)"
CERT="${PROJECT_DIR}/cert.pem"
KEY="${PROJECT_DIR}/key.pem"
PORT="${CANTEEN_PORT:-8901}"

cd "$PROJECT_DIR"

# ── Generate self-signed cert if missing ─────────────────────────────────────
if [ ! -f "$CERT" ] || [ ! -f "$KEY" ]; then
  echo "🔐 Generating self-signed HTTPS certificate..."
  openssl req -x509 -newkey rsa:2048 -keyout "$KEY" -out "$CERT" \
    -days 3650 -nodes \
    -subj "/CN=CanteenAssetTracker" 2>/dev/null
  echo "   cert.pem + key.pem created"
fi

# ── Install deps if needed ───────────────────────────────────────────────────
if [ ! -f "${PROJECT_DIR}/.deps_installed" ]; then
  echo "📦 Installing Python dependencies..."
  pip install -r requirements.txt -q
  touch "${PROJECT_DIR}/.deps_installed"
fi

# ── Clean stale DB? Controlled by env ────────────────────────────────────────
DB_PATH="${CANTEEN_DB_PATH:-${PROJECT_DIR}/assets.db}"
if [ "${CANTEEN_WIPE_DB:-}" = "1" ]; then
  echo "🧹 Wiping database: $DB_PATH"
  rm -f "$DB_PATH" "${DB_PATH}-shm" "${DB_PATH}-wal"
fi

# ── Back up existing DB before launch ─────────────────────────────────────────
if [ -f "$DB_PATH" ]; then
  BACKUP_DIR="/home/oplabs/backups/canteen-db"
  mkdir -p "$BACKUP_DIR"
  TIMESTAMP=$(date +%Y%m%d-%H%M%S)
  cp "$DB_PATH" "${BACKUP_DIR}/assets.db-${TIMESTAMP}"
  # Keep last 30 backups
  ls -t "${BACKUP_DIR}/assets.db-"* 2>/dev/null | tail -n +31 | xargs rm -f 2>/dev/null || true
  echo "   Backup: ${BACKUP_DIR}/assets.db-${TIMESTAMP}"
fi

# ── Launch ───────────────────────────────────────────────────────────────────
echo "🚀 Starting Canteen Asset Tracker on https://0.0.0.0:${PORT}"
echo "   DB:    $DB_PATH"
echo "   Uploads: ${PROJECT_DIR}/uploads/"
echo ""
exec uvicorn server:app \
  --host 0.0.0.0 \
  --port "$PORT" \
  --ssl-keyfile "$KEY" \
  --ssl-certfile "$CERT" \
  --log-level info
