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

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "${root}"

target="${EVERY_CHANNEL_FORGE_TARGET_HOST:-root@git.every.channel}"
build_host="${EVERY_CHANNEL_FORGE_BUILD_HOST:-${target}}"
identity_file="${EVERY_CHANNEL_FORGE_SSH_IDENTITY:-$HOME/.ssh/id_ed25519}"

if [[ ! -f "${identity_file}" ]]; then
  echo "error: SSH identity not found: ${identity_file}" >&2
  exit 2
fi

export NIX_SSHOPTS="-o BatchMode=yes -o IdentityAgent=none -o IdentitiesOnly=yes -i ${identity_file}"

exec nix run nixpkgs#nixos-rebuild -- \
  --flake "${root}#ecp-forge" \
  --target-host "${target}" \
  --build-host "${build_host}" \
  --use-remote-sudo \
  switch
