#!/usr/bin/env bash
# Stage 1 — convert Debian 12 → NixOS via nixos-infect (pinned revision).
#
# nixos-infect generates /etc/nixos/{configuration.nix,hardware-configuration.nix,networking.nix}
# with Hetzner-correct bootloader (GRUB, not systemd-boot) and networking, then reboots into NixOS.
#
# After the reboot:
#   - SSH as root is available (key registered with Hetzner survives infect)
#   - Run Stage 2 per terraform/README.md: clone cc-ci + cc-ci-secrets, provision the bootstrap
#     age key, then `nixos-rebuild switch --flake .#cc-ci-hetzner`
#
# Logs are written to /var/log/nixos-infect.log on the server for post-mortem inspection.
# The server reboots automatically at the end of infect — wait ~5 min before sshing in.
set -euo pipefail

# Pinned nixos-infect revision (2026-03-22: "fixes errors for non efi systems").
# Update deliberately; verify Hetzner still supported before bumping.
INFECT_SHA="40f62a680bb0e8f2f607d79abfaaecd99d59401c"

export NIX_CHANNEL="nixos-24.11"
export PROVIDER="hetzner" # tells nixos-infect to use GRUB + Hetzner networking
export NIXOS_IMPORT=""    # no extra imports at infect time; we apply the real flake in Stage 2

curl -fsSL "https://raw.githubusercontent.com/elitak/nixos-infect/${INFECT_SHA}/nixos-infect" |
  bash -x 2>&1 | tee /var/log/nixos-infect.log
