#!/bin/bash

## Copyright (C) 2026 - 2026 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## AI-Assisted

## Smoke-test the configured GitHub token before running
## dm-github-fork-sync / dm-github-org-policy. Prints the
## authenticated user login and the current REST API rate-limit
## budget, or fails with a clear error if the token is missing /
## invalid / over quota.
##
## Usage:
##   GITHUB_TOKEN='ghp_...' dm-github-token-test
## or, with a token file at ~/.config/github-token (chmod 600):
##   dm-github-token-test

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

# shellcheck source=../../../helper-scripts/usr/libexec/helper-scripts/log_run_die.sh
source "${HELPER_SCRIPTS_PATH:-}"/usr/libexec/helper-scripts/log_run_die.sh
# shellcheck source=../../../helper-scripts/usr/libexec/helper-scripts/has.sh
source "${HELPER_SCRIPTS_PATH:-}"/usr/libexec/helper-scripts/has.sh
# shellcheck source=../libexec/developer-meta-files/github-org-lib.bsh
source /usr/libexec/developer-meta-files/github-org-lib.bsh

ghorg_require_deps

login="$(ghorg_authenticated_user)" || die 1 'token rejected by /user'

## /rate_limit shows how much budget we have for the upcoming
## dm-github-fork-sync / dm-github-org-policy work; /user above proved
## the token is valid.
rl_result="$(ghorg_api GET '/rate_limit')" || die 1 '/rate_limit failed'

rl_status="$(ghorg_status_of "${rl_result}")"

[ "${rl_status}" = '200' ] || die 1 "/rate_limit returned HTTP '${rl_status}'"

rl_body="$(ghorg_body_of "${rl_result}")"

remaining="$(printf '%s' "${rl_body}" | ghorg_jq_capped -r -- '.resources.core.remaining')"
limit="$(printf '%s' "${rl_body}" | ghorg_jq_capped -r -- '.resources.core.limit')"
reset_epoch="$(printf '%s' "${rl_body}" | ghorg_jq_capped -r -- '.resources.core.reset')"

is_whole_number "${remaining}" || die 1 "non-numeric core.remaining: '${remaining}'"
is_whole_number "${limit}" || die 1 "non-numeric core.limit: '${limit}'"
is_whole_number "${reset_epoch}" || die 1 "non-numeric core.reset: '${reset_epoch}'"

reset_iso="$(date -u -d "@${reset_epoch}" '+%Y-%m-%dT%H:%M:%SZ')"

log notice "login: ${login}"
log notice "rate-limit core: ${remaining}/${limit} (resets at ${reset_iso})"

if [ "${remaining}" -lt 100 ]; then
  log warn "rate-limit core remaining is low (${remaining}/${limit}); consider waiting until reset"
fi
