#!/usr/bin/env bash
# Repin the norsk-ctl daemon in flake.nix to a channel version. Resolves the
# version (default: the `latest` channel), fetches each platform's sha256
# sidecar, converts to SRI, and rewrites `ctlVersion` + the four `hash =` lines
# in flake.nix in place. Run from anywhere; targets the flake.nix beside it.
#
#   refresh-ctl-pin.sh                       # pin to the current `latest`
#   refresh-ctl-pin.sh 0.1.0-2026-07-27-...  # pin to an explicit version
set -euo pipefail

here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
flake="$here/flake.nix"
base="https://s3.eu-west-1.amazonaws.com/norsk.video/norsk-ctl"

ver="${1:-$(curl -fsSL "$base/latest")}"
echo "pinning norsk-ctl -> $ver"

declare -A plat=(
  [x86_64-linux]=linux-x64
  [aarch64-linux]=linux-arm64
  [aarch64-darwin]=darwin-arm64
  [x86_64-darwin]=darwin-x64
)

# nix keys the ctlAsset attrset by system; rewrite each system's hash line. The
# hash lines live in the `ctlAsset = { ... }` block, one per platform string.
for sys in "${!plat[@]}"; do
  p="${plat[$sys]}"
  hex="$(curl -fsSL "$base/$ver/norsk-ctl-$ver-$p.sha256" | awk '{print $1}')"
  [ -n "$hex" ] || { echo "no sha256 sidecar for $p" >&2; exit 1; }
  sri="$(nix hash convert --hash-algo sha256 --to sri "$hex")"
  # Replace the hash on the line that mentions this platform's plat string.
  perl -0pi -e "s{(plat = \"$p\";\\s*hash = \")[^\"]*(\")}{\${1}$sri\${2}}" "$flake"
  echo "  $sys ($p): $sri"
done

perl -0pi -e "s{(ctlVersion = \")[^\"]*(\")}{\${1}$ver\${2}}" "$flake"
echo "updated $flake"
echo "this is the starter's pin; each product's own flake.nix is bumped nightly by bump.yml"
