# SPDX-FileCopyrightText: 2024 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ depot, system, pkgs, ... }:
pkgs.writeShellApplication {
  name = "switch-prebuilt";

  runtimeInputs = with pkgs; [ curl unzip jq ];

  text = ''
    set -ue
    system="''${1}"

    if [[ "$system" == "latest" ]]; then
      tmpdir="$(mktemp -d)"
      trap '{ rm -rf -- "$tmpdir"; }' EXIT

      COMMIT_DATA="$(curl -s 'https://hg.lukegb.com/api/v4/projects/lukegb%2Fdepot/repository/commits/branch%2Fdefault')"
      echo "Commit: $(echo "$COMMIT_DATA" | jq -r '.id') $(echo "$COMMIT_DATA" | jq -r '.title')"
      if [[ "$(echo "$COMMIT_DATA" | jq -r '.last_pipeline.id')" == null ]]; then
        echo "...but there's no CI pipeline for it"
        exit 1
      fi

      PARENT_PIPELINE_BRIDGES="$(curl -s "https://hg.lukegb.com/api/v4/projects/lukegb%2Fdepot/pipelines/$(echo "$COMMIT_DATA" | jq -r '.last_pipeline.id')/bridges")"
      if [[ "$(echo "$PARENT_PIPELINE_BRIDGES" | jq -r '. | length')" == 0 ]]; then
        echo "...but there's no downstream pipeline for it"
        exit 1
      fi
      CHILD_PIPELINE_ID="$(echo "$PARENT_PIPELINE_BRIDGES" | jq -r '.[].downstream_pipeline.id')"
      CHILD_PIPELINE_JOBS="$(curl -s "https://hg.lukegb.com/api/v4/projects/lukegb%2Fdepot/pipelines/$CHILD_PIPELINE_ID/jobs?per_page=100")"
      CACHE_JOB_ID="$(echo "$CHILD_PIPELINE_JOBS" | jq -r '.[] | select(.name == "nixCache-linux") | .id')"
      if [[ "$CACHE_JOB_ID" == "" ]]; then
        echo "...but there's no data for the cache job"
        exit 1
      fi

      curl -so "$tmpdir/systems.json" "https://hg.lukegb.com/api/v4/projects/lukegb%2Fdepot/jobs/$CACHE_JOB_ID/artifacts/systems.json"
      system="$(jq -r ".\"$(hostname)\"" "$tmpdir/systems.json")"

      echo "Switching to system ''$system"
    fi

    if [[ ! -e "$system" ]]; then
      # We should be a trusted-user.
      nix build -v "$system"
    fi

    diff "$system/etc/hostname" "/etc/hostname"

    # The next phase requires sudo, but it's harmless to run the preceding commands twice.
    if [[ $EUID -ne 0 ]]; then
      exec sudo "$0" "$system"
    fi

    nix-env -p /nix/var/nix/profiles/system --set "$system"
    "$system/bin/switch-to-configuration" switch
  '';
}