#!/usr/bin/env bash
# This script assigns custom property values to repositories using GitHub's REST API.
# It reads from a JSON descriptor (repo_properties.json) and issues PATCH requests.
# Requirements: jq, curl, and a GitHub personal access token with admin:org scope.

set -euo pipefail

# Personal access token must be provided via the GITHUB_TOKEN environment
# variable or an `.env` file.  This script does not prompt for input.  If
# GITHUB_TOKEN is not set, the script attempts to load it from a local
# `.env` file.  If the token remains unset after loading, the script exits
# with an error.  This avoids interactive prompts and encourages secret
# management via environment files or CI secrets.
if [ -z "${GITHUB_TOKEN:-}" ]; then
  # Attempt to load from .env if it exists
  if [ -f ".env" ]; then
    set -a
    . ./.env
    set +a
  fi
fi

if [ -z "${GITHUB_TOKEN:-}" ]; then
  echo "Error: GITHUB_TOKEN is not set.  Please define it in your environment or in an .env file." >&2
  exit 1
fi

# Path to JSON descriptor file.  Adjust if you place it elsewhere.
PROPERTIES_FILE="repo_properties.json"

if [ ! -f "$PROPERTIES_FILE" ]; then
  echo "Descriptor file $PROPERTIES_FILE not found. Abort."
  exit 1
fi

# Iterate over each repository entry in the JSON
jq -r 'to_entries[] | "\(.key)\u0000\(.value|tostring)"' "$PROPERTIES_FILE" | while IFS=$'\u0000' read -r repo props; do
  owner="${repo%%/*}"
  repo_name="${repo#*/}"

  # Build payload: { "properties": [ { "property_name": ..., "value": ... }, ... ] }
  payload=$(echo "$props" | jq '{ properties: [ to_entries[] | { property_name: .key, value: .value } ] }')

  echo "Assigning properties to $repo_name in $owner..."
  response=$(curl -sS -X PATCH \
    -H "Accept: application/vnd.github+json" \
    -H "Authorization: Bearer $GITHUB_TOKEN" \
    "https://api.github.com/repos/$owner/$repo_name/properties/values" \
    -d "$payload")

  if echo "$response" | jq -e '.error' >/dev/null; then
    echo "Failed to assign properties for $repo: $(echo "$response" | jq -r '.error')" >&2
  else
    echo "Successfully assigned properties for $repo."
  fi

done

