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

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

cache_server_name="${BURROW_NIX_CACHE_SERVER_NAME:-burrow}"
cache_server_url="${BURROW_NIX_CACHE_SERVER_URL:-https://nix.burrow.net}"
cache_name="${BURROW_NIX_CACHE_NAME:-burrow}"
cache_ref="${cache_server_name}:${cache_name}"
token="${BURROW_NIX_CACHE_PUSH_TOKEN:-}"

if [[ -z "$token" ]]; then
  if [[ "${BURROW_NIX_CACHE_REQUIRED:-false}" == "true" ]]; then
    echo "BURROW_NIX_CACHE_PUSH_TOKEN is required to publish Nix cache paths" >&2
    exit 1
  fi
  echo "::notice ::BURROW_NIX_CACHE_PUSH_TOKEN is not set; skipping Nix cache publish."
  exit 0
fi

if ! command -v attic >/dev/null 2>&1; then
  echo "attic is required to publish Nix cache paths" >&2
  exit 127
fi

if ! command -v nix >/dev/null 2>&1; then
  echo "nix is required to build paths for cache publishing" >&2
  exit 127
fi

attic login "$cache_server_name" "$cache_server_url" "$token" --set-default

push_inputs=("$@")
if [[ "${#push_inputs[@]}" -eq 0 ]]; then
  read -r -a attrs <<< "${BURROW_NIX_CACHE_ATTRS:-.#burrow .#forgejo-nsc-dispatcher .#forgejo-nsc-autoscaler}"
  if [[ "${#attrs[@]}" -eq 0 ]]; then
    echo "no Nix attrs were supplied for cache publishing" >&2
    exit 1
  fi
  mapfile -t push_inputs < <(nix build --no-link --print-out-paths "${attrs[@]}")
fi

if [[ "${#push_inputs[@]}" -eq 0 ]]; then
  echo "no Nix output paths were produced for cache publishing" >&2
  exit 1
fi

attic push "$cache_ref" "${push_inputs[@]}"
