#!/usr/bin/env nix-shell
#!nix-shell -i bash -p curl nix jq
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
VERSIONS_URL="https://versions.brave.com/latest/brave-versions.json"

sri_hash() {
  nix-hash --to-sri --type sha256 "$(nix-prefetch-url --type sha256 "$1")"
}

find_release_with_asset() {
  local versionsJson="$1" channel="$2" template="$3"
  local match
  match="$(
    jq -c --arg channel "$channel" --arg tmpl "$template" '
      [.[]
      | select(.channel == $channel)
      | . as $r
      | select(
          $r.github.assets
          | map(.name)
          | any(. == ($tmpl | gsub("\\$\\{version\\}"; $r.name)))
        )
      ]
      | sort_by(.published)
      | last
    ' <<<"$versionsJson"
  )"
  if [[ "$match" != "null" ]]; then
    printf '%s' "$match"
    return 0
  fi
  echo "update.sh: no ${channel} release with asset matching '${template}' found" >&2
  return 1
}

emit_archive_entry() {
  local releaseJson="$1" version="$2" template="$3" platform="$4"
  local name="${template//\$\{version\}/$version}"
  local url
  url="$(
    jq -r --arg n "$name" '
      .github.assets[]
      | select(.name == $n)
      | .download_url
    ' <<<"$releaseJson"
  )"
  if [[ -z "$url" ]]; then
    return 0
  fi
  local hash
  hash="$(sri_hash "$url")"
  local nixUrl="${url//${version}/\$\{version\}}"
  cat <<EOF
    ${platform} = {
      url = "${nixUrl}";
      hash = "${hash}";
    };
EOF
}

write_package_nix() {
  local pname="$1" releaseJson="$2" debStem="$3" darwinStem="$4"
  local version
  version="$(jq -r '.name' <<<"$releaseJson")"
  echo "=> ${pname}: ${version}" >&2
  local flavorLine=""
  if [[ "$pname" == brave-origin || "$pname" == brave-origin-* ]]; then
    flavorLine='  flavor = "origin";'
  fi
  local outFile="${SCRIPT_DIR}/packages/${pname}.nix"
  {
    echo '# Expression generated by update.sh; do not edit it by hand!'
    echo 'rec {'
    echo "  pname = \"${pname}\";"
    echo "  version = \"${version}\";"
    [[ -n "$flavorLine" ]] && echo "$flavorLine"
    echo ''
    echo '  archives = {'
    emit_archive_entry "$releaseJson" "$version" "${debStem}_\${version}_arm64.deb"      "aarch64-linux"
    emit_archive_entry "$releaseJson" "$version" "${debStem}_\${version}_amd64.deb"      "x86_64-linux"
    emit_archive_entry "$releaseJson" "$version" "${darwinStem}-v\${version}-darwin-arm64.zip" "aarch64-darwin"
    echo '  };'
    echo '}'
  } > "$outFile"
}

versionsJson="$(curl --fail -s "$VERSIONS_URL")"

entries=(
  "brave                brave-browser         brave"
  "brave-origin         brave-origin          brave-origin"
)

for entry in "${entries[@]}"; do
  read -r pname debStem darwinStem <<<"$entry"
  releaseJson="$(find_release_with_asset "$versionsJson" "release" "${debStem}_\${version}_amd64.deb")"
  write_package_nix "$pname" "$releaseJson" "$debStem" "$darwinStem"
done
