#!/bin/bash
# One-time server setup for XAMXAM
# Run this before the first deploy (or after a permission reset).
#
# Usage: just setup-server
#    or: sudo DEPLOY_USER=youruser bash /tmp/setup-server.sh

set -e

# ── Colors / helpers ──────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

ok()   { printf "${GREEN}✓${NC} %s\n" "$*"; }
warn() { printf "${YELLOW}!${NC} %s\n" "$*"; }
die()  { printf "${RED}✗${NC} %s\n" "$*" >&2; exit 1; }
# ─────────────────────────────────────────────────────────────────────────────

[ "$EUID" -eq 0 ] || die "Run as root (sudo)"

# ── Config ────────────────────────────────────────────────────────────────────
# DEPLOY_USER is passed explicitly by the justfile (read from ~/.ssh/config via
# `ssh -G xamxam`). Falls back to $SUDO_USER if run manually with sudo.
DEPLOY_USER="${DEPLOY_USER:-${SUDO_USER}}"
[ -n "$DEPLOY_USER" ] || die "DEPLOY_USER is not set. Pass it explicitly: sudo DEPLOY_USER=youruser bash $0"
APP_DIR="/var/www/xamxam"
APP_GROUP="xamxam"
WEB_USER="www-data"
# ─────────────────────────────────────────────────────────────────────────────

printf "🔧 XAMXAM Server Setup\n"
printf "====================\n\n"

# ── 1. Create xamxam group ───────────────────────────────────────────────────
if ! getent group "$APP_GROUP" >/dev/null; then
    groupadd "$APP_GROUP"
    ok "Created group: $APP_GROUP"
else
    ok "Group already exists: $APP_GROUP"
fi

# ── 2. Add deploy user and web user to group ──────────────────────────────────
for user in "$DEPLOY_USER" "$WEB_USER"; do
    if id "$user" &>/dev/null; then
        if ! id -nG "$user" | grep -qw "$APP_GROUP"; then
            usermod -aG "$APP_GROUP" "$user"
            ok "Added $user to $APP_GROUP"
        else
            ok "$user already in $APP_GROUP"
        fi
    else
        warn "User $user not found — skipping"
    fi
done

# ── 3. Create app directory ───────────────────────────────────────────────────
mkdir -p "$APP_DIR"
ok "Ensured $APP_DIR exists"

# ── 4. Set ownership ──────────────────────────────────────────────────────────
chown -R "$WEB_USER:$APP_GROUP" "$APP_DIR"
ok "Ownership: $WEB_USER:$APP_GROUP on $APP_DIR"

# ── 5. Set directory permissions with setgid ──────────────────────────────────
# 2775 = rwxrwsr-x
#   - owner (www-data) and group (xamxam) can read/write/execute
#   - setgid bit ensures new files/dirs inherit the xamxam group
#   - this is what allows rsync --chown=www-data:xamxam to succeed
find "$APP_DIR" -type d -exec chmod 2775 {} \;
ok "Directories: 2775 (setgid) on $APP_DIR/**"

# ── 6. Set file permissions ───────────────────────────────────────────────────
find "$APP_DIR" -type f -exec chmod 664 {} \;
ok "Files: 664 on $APP_DIR/**"

# ── 7. Tighten storage ───────────────────────────────────────────────────────
if [ -d "$APP_DIR/storage" ]; then
    chmod 2775 "$APP_DIR/storage"
    find "$APP_DIR/storage" -name "*.db" -exec chmod 660 {} \;
    ok "Storage: 2775, databases: 660"
fi

# Ensure writable cache subdirectories exist for php-fpm (www-data)
mkdir -p "$APP_DIR/storage/cache/rate_limit"
chown -R "$WEB_USER:$APP_GROUP" "$APP_DIR/storage/cache"
chmod -R 2775 "$APP_DIR/storage/cache"
ok "Cache dirs: created and owned by $WEB_USER:$APP_GROUP"

# ── 8. Provision /var/log/xamxam.log ─────────────────────────────────────────
if [ ! -f /var/log/xamxam.log ]; then
    touch /var/log/xamxam.log
fi
chown "$WEB_USER:$APP_GROUP" /var/log/xamxam.log
chmod 640 /var/log/xamxam.log
ok "/var/log/xamxam.log: owned by $WEB_USER:$APP_GROUP (640)"

printf "\n"
ok "Setup complete."
printf "\nNext steps:\n"
printf "  1. Log out and back in as '%s' so group membership takes effect\n" "$DEPLOY_USER"
printf "     (or run: newgrp %s)\n" "$APP_GROUP"
printf "  2. Run: just deploy\n\n"
warn "If this is a fresh server, also run after first deploy:"
printf "     just deploy-db        # push initial database\n"
printf "     just deploy-nginx     # install nginx config\n"
