#!/usr/bin/env bash
# Aurora Deck — Raspberry Pi Setup Script
#
# Installs Docker, downloads the Aurora Deck docker-compose file, generates
# secret keys, and registers a systemd service so Aurora Deck starts
# automatically on every boot.
#
# Run this on your Raspberry Pi after completing the initial setup steps:
#   bash setup-aurora-deck-pi.sh

set -euo pipefail

AURORA_DIR="$HOME/aurora-deck"
SERVICE_USER="${USER:-pi}"
COMPOSE_URL="https://auroradeck.com/aurora-deck-docker-compose.yaml"

# ── Helper ────────────────────────────────────────────────────────────────────
info()  { echo "[aurora] $*"; }
warn()  { echo "[aurora] WARNING: $*" >&2; }
abort() { echo "[aurora] ERROR: $*" >&2; exit 1; }

# ── Require root access ───────────────────────────────────────────────────────
if ! sudo -n true 2>/dev/null; then
  info "This script needs sudo for Docker installation and systemd setup."
  sudo -v
fi

# ── 1. Install Docker ─────────────────────────────────────────────────────────
if command -v docker &>/dev/null; then
  info "Docker is already installed ($(docker --version))."
else
  info "Installing Docker..."
  curl -fsSL https://get.docker.com | sh
  info "Adding $SERVICE_USER to the docker group..."
  sudo usermod -aG docker "$SERVICE_USER"
fi

# ── 2. Create aurora-deck directory ──────────────────────────────────────────
info "Creating $AURORA_DIR..."
mkdir -p "$AURORA_DIR"
cd "$AURORA_DIR"

# ── 3. Download docker-compose file ──────────────────────────────────────────
if [ -f docker-compose.yaml ]; then
  warn "docker-compose.yaml already exists — skipping download."
else
  info "Downloading docker-compose.yaml..."
  curl -fsSL "$COMPOSE_URL" -o docker-compose.yaml
fi

# ── 4. Generate secrets ───────────────────────────────────────────────────────
JWT_SECRET="$(openssl rand -hex 32)"
OAUTH_SECRET="$(openssl rand -hex 16)"

info "Generated secrets — updating docker-compose.yaml..."

# Replace the commented-out placeholders with real values
sed -i \
  "s|# JWT_SECRET: <CHANGE_ME>|JWT_SECRET: $JWT_SECRET|" \
  docker-compose.yaml

sed -i \
  "s|# OAUTH_STATE_SECRET_KEY: <CHANGE_ME>|OAUTH_STATE_SECRET_KEY: $OAUTH_SECRET|" \
  docker-compose.yaml

echo ""
echo "  JWT_SECRET and OAUTH_STATE_SECRET_KEY have been set automatically."
echo "  If you need Google Calendar or Photos, open the file and fill in:"
echo "    GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, CALENDAR_TOKEN_KEY, PHOTOS_TOKEN_KEY"
echo ""
echo "  File location: $AURORA_DIR/docker-compose.yaml"
echo ""
read -rp "Press Enter to continue (or Ctrl-C to edit the file first)..."

# ── 5. Register systemd service ───────────────────────────────────────────────
info "Registering aurora-deck systemd service..."
sudo tee /etc/systemd/system/aurora-deck.service > /dev/null << EOF
[Unit]
Description=Aurora Deck
Documentation=https://auroradeck.com/self-hosting
After=docker.service network-online.target
Requires=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=$AURORA_DIR
ExecStart=/usr/bin/docker compose up -d
ExecStop=/usr/bin/docker compose down
User=$SERVICE_USER
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# ── 6. Enable and start ───────────────────────────────────────────────────────
info "Enabling aurora-deck service..."
sudo systemctl daemon-reload
sudo systemctl enable aurora-deck

info "Pulling Docker images (this may take a few minutes)..."
docker compose -f "$AURORA_DIR/docker-compose.yaml" pull

info "Starting Aurora Deck..."
sudo systemctl start aurora-deck

echo ""
echo "  Aurora Deck is running at http://localhost:8080"
echo "  It will start automatically on every boot."
echo ""
echo "  Rebooting in 10 seconds to apply Docker group membership..."
echo "  (Press Ctrl-C to skip the reboot and reboot manually later.)"
echo ""
sleep 10
sudo reboot
