#!/bin/zsh -Ndefgku
#
# Scripts/generate_token
# mas
#
# Copyright © 2025 mas-cli. All rights reserved.
#
# Generates a GitHub App installation access token for GitHub Workflows.
#

. "${0:A:h}/_setup_script"

readonly header=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9
readonly payload="${${$(printf '{"iss":%s,"iat":%s,"exp":%s}' "${TOKEN_APP_ID}" "$(("$(date +%s)" - 60))"\
	"$(("$(date +%s)" + 540))" | base64)//[=$'\n']}//\/+/_-}"

# shellcheck disable=SC1036,SC1072,SC1073
curl\
	-sX POST\
	-H "Authorization: Bearer ${header}.${payload}.${${$(printf %s "${header}.${payload}" |
	openssl dgst -sha256 -sign =(printf %s "${TOKEN_APP_PRIVATE_KEY}") | base64)//[=$'\n']}//\/+/_-}"\
	-H 'Accept: application/vnd.github+json'\
	"https://api.github.com/app/installations/${TOKEN_APP_INSTALLATION_ID}/access_tokens" |
	jq -r .token
