#!/usr/bin/env bash
set -euo pipefail

REPO="theMackabu/ant"
WORKFLOW="build.yml" # Target the specific workflow file name
INSTALL_DIR="${HOME}/.ant/bin"

AUTH_HEADER=()
if [ -n "${GH_TOKEN:-}" ]; then
  echo "--> Using supplied GH_TOKEN for API authentication."
  AUTH_HEADER=(-H "Authorization: Bearer ${GH_TOKEN}")
else
  echo "--> WARNING: GH_TOKEN is not set. Artifact download via GitHub API will likely fail without auth."
fi

# 1. Fetch latest successful run ID FOR THIS SPECIFIC WORKFLOW
echo "--> Fetching latest successful '${WORKFLOW}' run on branch 'master' for ${REPO}..."
RUN_RESPONSE=$(curl -sSL "${AUTH_HEADER[@]}" \
  "https://api.github.com/repos/${REPO}/actions/workflows/${WORKFLOW}/runs?branch=master&status=success")

# Extract the "id" value inside the first workflow run block
RUN_ID=$(echo "${RUN_RESPONSE}" | tr -d '\n' | sed -n 's/.*"workflow_runs":\s*\[\s*{\s*"id":\s*\([0-9]*\).*/\1/p')

if [ -z "${RUN_ID}" ]; then
  echo "--> Error: Could not find a successful '${WORKFLOW}' run."
  echo "    API Response: ${RUN_RESPONSE}"
  exit 1
fi
echo "    Found target workflow run ID: ${RUN_ID}"

# 2. Get artifact download URL
echo "--> Fetching artifact list for run ID ${RUN_ID}..."
ARTIFACT_RESPONSE=$(curl -sSL "${AUTH_HEADER[@]}" \
  "https://api.github.com/repos/${REPO}/actions/runs/${RUN_ID}/artifacts")

# Extract archive_download_url for the entry named "ant-linux-x64"
DOWNLOAD_URL=$(echo "${ARTIFACT_RESPONSE}" | tr -d '\n' | sed -E 's/\}/\}\n/g' | grep '"name":\s*"ant-linux-x64"' | sed -n 's/.*"archive_download_url":\s*"\([^"]*\)".*/\1/p' | sed 's/\\//g')

if [ -z "${DOWNLOAD_URL}" ]; then
  echo "--> Error: Artifact 'ant-linux-x64' not found in run ${RUN_ID}."
  AVAILABLE_NAMES=$(echo "${ARTIFACT_RESPONSE}" | tr -d '\n' | sed -E 's/\}/\}\n/g' | grep -o '"name":\s*"[^"]*"' | cut -d'"' -f4 | tr '\n' ' ')
  echo "    Available artifacts: [ ${AVAILABLE_NAMES}]"
  exit 1
fi
echo "    Found artifact download URL: ${DOWNLOAD_URL}"

# 3. Download the artifact (following redirects with -L)
echo "--> Downloading 'ant-linux-x64' artifact to ant-ci-build.zip..."
curl -sSL "${AUTH_HEADER[@]}" -L -o ant-ci-build.zip "${DOWNLOAD_URL}"

# Validate file integrity before extracting
if ! file ant-ci-build.zip | grep -qi 'zip archive'; then
  echo "--> Error: Downloaded file is not a valid ZIP archive."
  echo "    Server response content:"
  cat ant-ci-build.zip
  echo ""
  echo "    Note: Downloading GitHub Actions artifacts via API requires setting GH_TOKEN."
  rm -f ant-ci-build.zip
  exit 1
fi

# 4. Extract and install to user home directory
echo "--> Extracting artifact..."
mkdir -p ant-ci-build
unzip -qo ant-ci-build.zip -d ant-ci-build

echo "--> Installing ant binary to ${INSTALL_DIR}/ant..."
mkdir -p "${INSTALL_DIR}"
chmod +x ant-ci-build/ant
install -m 755 ant-ci-build/ant "${INSTALL_DIR}/ant"

# Cleanup build files
rm -rf ant-ci-build ant-ci-build.zip

# Ensure PATH includes ~/.ant/bin for current execution
export PATH="${INSTALL_DIR}:${PATH}"

echo "--> Installation complete! Running 'ant --version':"
"${INSTALL_DIR}/ant" --version