#!/bin/bash
# Multithreaded Deployment Script — Hetzner (alpha-west-1)
# Cross-compiles for x86_64 Linux on macOS, uploads, restarts.
# Run from the multithreaded project root.
#
# Usage:
#   ./deploy/deploy-hetzner.sh              # Build + deploy + restart
#   ./deploy/deploy-hetzner.sh --setup      # First-time: create user, dirs, db, build, install, seed
#   ./deploy/deploy-hetzner.sh --config     # Config only (Caddyfile, systemd, static, env)
#
# Prerequisites (one-time):
#   brew install zig
#   cargo install cargo-zigbuild
#   rustup target add x86_64-unknown-linux-gnu

set -e

# Configuration
SERVER="root@100.120.174.96"
REMOTE_DIR="/opt/multithreaded"
BINARY_NAME="multithreaded"
TARGET="x86_64-unknown-linux-gnu"
DEPLOY_DIR="deploy"

# Check we're in the right directory
if [ ! -f "Cargo.toml" ] || ! grep -q 'name = "multithreaded"' Cargo.toml; then
    echo "Error: Run this script from the MNW/multithreaded/ directory"
    exit 1
fi

build_binary() {
    echo "[build] Cross-compiling for $TARGET..."
    ulimit -n 65536 2>/dev/null || true
    cargo zigbuild --release --target $TARGET
    echo "[build] Done: target/$TARGET/release/$BINARY_NAME"
}

upload_config() {
    echo "[config] Uploading configuration files..."

    # Systemd service
    scp $DEPLOY_DIR/multithreaded.service $SERVER:/etc/systemd/system/multithreaded.service

    # Static assets
    echo "[config] Uploading static assets..."
    ssh $SERVER "mkdir -p $REMOTE_DIR/static $REMOTE_DIR/migrations"
    rsync -az --delete static/ $SERVER:$REMOTE_DIR/static/
    rsync -az --delete migrations/ $SERVER:$REMOTE_DIR/migrations/

    # Fix ownership
    ssh $SERVER "chown -R multithreaded:multithreaded $REMOTE_DIR"

    # Reload systemd
    ssh $SERVER "systemctl daemon-reload"
    echo "[config] Done"
}

upload_binary() {
    echo "[upload] Stopping service and uploading binary..."
    ssh $SERVER "systemctl stop multithreaded || true"
    scp target/$TARGET/release/$BINARY_NAME $SERVER:$REMOTE_DIR/$BINARY_NAME
    ssh $SERVER "chmod +x $REMOTE_DIR/$BINARY_NAME && chown multithreaded:multithreaded $REMOTE_DIR/$BINARY_NAME"
    echo "[upload] Done"
}

restart_app() {
    echo "[restart] Restarting multithreaded..."
    ssh $SERVER "systemctl restart multithreaded"
    sleep 2
    echo ""
    ssh $SERVER "systemctl status multithreaded --no-pager"
    echo ""
    echo "[health] Checking..."
    ssh $SERVER "curl -s -o /dev/null -w 'HTTP %{http_code}\n' http://127.0.0.1:3400/"
}

first_time_setup() {
    echo "=== First-Time Setup (Hetzner) ==="

    echo "[setup] Creating system user..."
    ssh $SERVER "
        useradd --system --shell /usr/sbin/nologin --home-dir $REMOTE_DIR multithreaded 2>/dev/null || echo 'User already exists'
    "

    echo "[setup] Creating directories..."
    ssh $SERVER "
        mkdir -p $REMOTE_DIR
        chown multithreaded:multithreaded $REMOTE_DIR
    "

    echo "[setup] Creating database role + database..."
    ssh $SERVER "
        sudo -u postgres createuser multithreaded 2>/dev/null || echo 'Role already exists'
        sudo -u postgres createdb -O multithreaded multithreaded 2>/dev/null || echo 'Database already exists'
        sudo -u postgres psql -c 'GRANT ALL PRIVILEGES ON DATABASE multithreaded TO multithreaded;' 2>/dev/null
        sudo -u postgres psql -d multithreaded -c 'GRANT ALL ON SCHEMA public TO multithreaded;' 2>/dev/null
    "

    build_binary
    upload_config

    echo "[setup] Installing binary..."
    upload_binary

    echo "[setup] Installing env file..."
    scp $DEPLOY_DIR/env.hetzner $SERVER:$REMOTE_DIR/.env
    ssh $SERVER "chmod 600 $REMOTE_DIR/.env && chown multithreaded:multithreaded $REMOTE_DIR/.env"

    echo "[setup] Enabling and starting service..."
    ssh $SERVER "systemctl enable multithreaded && systemctl start multithreaded"
    sleep 2

    echo "[setup] Running seed..."
    ssh $SERVER "cd $REMOTE_DIR && sudo -u multithreaded $REMOTE_DIR/$BINARY_NAME --seed"

    echo ""
    ssh $SERVER "systemctl status multithreaded --no-pager"
    echo ""
    echo "[health] Checking..."
    ssh $SERVER "curl -s -o /dev/null -w 'HTTP %{http_code}\n' http://127.0.0.1:3400/"
}

case "${1:-deploy}" in
    --setup)
        first_time_setup
        ;;
    --config)
        echo "=== Config Deploy (Hetzner) ==="
        upload_config
        ;;
    deploy|"")
        echo "=== Deploy (Hetzner) ==="
        build_binary
        upload_config
        upload_binary
        restart_app
        ;;
    *)
        echo "Usage: $0 [--setup|--config]"
        exit 1
        ;;
esac

echo ""
echo "=== Done ==="
