#!/usr/bin/env bash
#
# This script demonstrates a simple pattern for safely managing your GitHub
# Personal Access Token (PAT) using an environment file.  It copies a
# template `.env.example` to `.env` if it does not yet exist, and then
# loads the `GITHUB_TOKEN` variable from `.env` into the current shell
# session.  The token can then be used by other scripts (e.g. `set_properties.sh`).
#
# Usage:
#   1. Run this script once to generate `.env` from `.env.example`.
#   2. Edit the newly created `.env` and replace the placeholder with your PAT.
#   3. Run this script again (or source `.env` directly) before executing
#      `set_properties.sh` to load the token into your environment.

set -euo pipefail

ENV_FILE=".env"
TEMPLATE_FILE=".env.example"

if [ ! -f "$ENV_FILE" ]; then
  if [ -f "$TEMPLATE_FILE" ]; then
    cp "$TEMPLATE_FILE" "$ENV_FILE"
    echo "Created $ENV_FILE from $TEMPLATE_FILE."
    echo "Please edit $ENV_FILE and set your GITHUB_TOKEN before running this script again."
    exit 0
  else
    echo "Template file $TEMPLATE_FILE not found. Cannot create $ENV_FILE." >&2
    exit 1
  fi
fi

# Export variables defined in the .env file.  'set -a' automatically exports
# variables sourced from the file.  After sourcing, we disable automatic export.
set -a
. "$ENV_FILE"
set +a

if [ -z "${GITHUB_TOKEN:-}" ]; then
  echo "Error: GITHUB_TOKEN is not set in $ENV_FILE." >&2
  echo "Please edit $ENV_FILE and set your token before running this script." >&2
  exit 1
fi

echo "GITHUB_TOKEN loaded for this session."