#!/usr/bin/env bash
set -euo pipefail

# Deploy NixOS to a Hetzner VPS using nixos-anywhere
# Usage: ./deploy.sh [user@host]
#
# IMPORTANT: Run this from a SEPARATE machine with Nix installed
# (laptop, another VPS, etc.), NOT from the target VPS itself.
# nixos-anywhere uses kexec to reboot the target; you can't reboot
# the machine you're running on.
#
# Steps:
#   1. git clone <this-repo> && cd nixos-config
#   2. Add your SSH pubkey to ./hosts/hetzner/users.nix
#   3. ./deploy.sh root@<vps-ip>
#
# This wipes the target disk and installs NixOS fresh.

HOST=${1:-root@localhost}

echo "=== Deploying NixOS to $HOST ==="
echo "WARNING: This will WIPE the target disk!"
read -rp "Continue? [y/N] " confirm
[[ "$confirm" =~ ^[Yy]$ ]] || exit 1

nix run github:nix-community/nixos-anywhere -- \
  --generate-hardware-config nixos-generate-config ./hosts/hetzner/hardware-configuration.nix \
  --flake ".#hetzner" "$HOST"

# After deploy, the generated hw config MUST be imported to flake.nix
echo ""
echo "=== CRITICAL: Post-deploy steps! ==="
echo "1. Import the generated hw config into flake.nix:"
echo "   git add hosts/hetzner/hardware-configuration.nix"
echo "   # In flake.nix, add to modules array:"
echo "       ./hosts/hetzner/hardware-configuration.nix"
echo ""
echo "2. Copy the age key to the new system for sops-nix:"
echo "   # From the deploy machine:"
echo "   ssh root@<new-ip> 'mkdir -p /etc/age'"
echo "   scp /home/admin/age/keys.txt root@<new-ip>:/etc/age/keys.txt"
echo ""
echo "3. IMPORTANT: The old gitea_db Docker Postgres needs migration."
echo "   The pg_dump is at /tmp/gitea-db-dump-YYYY-MM-DD.sql.gz"
echo "   Restore with:"
echo "   sudo -u postgres psql -c \"CREATE DATABASE gitea;\""
echo "   sudo -u postgres psql -c \"CREATE USER gitea WITH PASSWORD 'gitea';\""
echo "   sudo -u postgres psql -c \"GRANT ALL PRIVILEGES ON DATABASE gitea TO gitea;\""
echo "   zcat /tmp/gitea-db-dump-YYYY-MM-DD.sql.gz | sudo -u postgres psql gitea"
echo ""
echo "4. Restore Caddy certs for the mailserver:"
echo "   # The old Debian Caddy certs were backed up at /home/admin/backups/caddy-certs-mail.tar.gz"
echo "   # On NixOS Caddy stores at /var/lib/caddy/certificates/..."
echo ""
