#!/usr/bin/env nix-shell
#!nix-shell -I nixpkgs=./. -i bash -p curl jq nix-prefetch common-updater-scripts nix coreutils
# shellcheck shell=bash
set -euo pipefail

RELEASE_NAME=$(curl -s https://api.github.com/repos/infisical/infisical/releases \
  | jq -r 'sort_by(.created_at) | reverse |
           (map
             (select ((.prerelease == false) and (.draft == false) and (.name | contains("infisical-cli")))) |
             first
           ) | .name')
VERSION=$(echo "$RELEASE_NAME" | sed -E 's/^infisical-cli\/v//')

echo "Latest infisical release: $VERSION"

ARCHS=(
    "x86_64-linux:linux_amd64"
    "x86_64-darwin:darwin_amd64"
    "aarch64-linux:linux_arm64"
    "aarch64-darwin:darwin_arm64"
)

NFILE=pkgs/development/tools/infisical/default.nix
HFILE=pkgs/development/tools/infisical/hashes.json
rm -f "$HFILE" && touch "$HFILE"

printf "{ \"_comment\": \"@generated by pkgs/development/tools/infisical/update.sh\"\n" >> "$HFILE"

for arch in "${ARCHS[@]}"; do
    IFS=: read -r arch_name arch_target <<< "$arch"
    sha256hash="$(nix-prefetch-url --type sha256 "https://github.com/infisical/infisical/releases/download/${RELEASE_NAME}/infisical_${VERSION}_${arch_target}.tar.gz")"
    srihash="$(nix --extra-experimental-features nix-command hash to-sri --type sha256 "$sha256hash")"
    echo ", \"$arch_name\": \"$srihash\"" >> "$HFILE"
done
echo "}" >> "$HFILE"

sed -i \
  '0,/version\s*=\s*".*";/s//version = "'"$VERSION"'";/' \
  "$NFILE"

echo "Done; wrote $HFILE and updated version in $NFILE."
