#!/usr/bin/env bash
# get_oe4si_token.sh — Retrieve an AWS CodeArtifact token to configure maven and npm
#
# Usage:
#   export CODEARTIFACT_API_KEY="api-key"
#   source get_oe4si_token.sh                    # Configure the current environment
#
# Environment variables:
#   CODEARTIFACT_API_KEY   AWS CodeArtifact API Key (required)
#   TOKEN_ENDPOINT         AWS CodeArtifact Token generator endpoint
#   DOMAIN_ENDPOINT        <domain>-<account>.d.codeartifact.<region>.amazonaws.com
#   REPO_NAME              AWS CodeArtifact Repository name

set -euo pipefail

# ── Colors ──────────────────────────────────────────────────────────────────
if [[ -z "${CI:-}" ]]; then
    RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
else
    RED=''; GREEN=''; YELLOW=''; CYAN=''; NC=''
fi

# ── Configuration —──────────────────────────────────────────────────────────
TOKEN_ENDPOINT="${TOKEN_ENDPOINT:-https://smb1ubcf7c.execute-api.eu-west-3.amazonaws.com/prod/token}"
DOMAIN_ENDPOINT="${DOMAIN_ENDPOINT:-obeo-880882846414.d.codeartifact.eu-west-3.amazonaws.com}"
REPO_NAME="${REPO_NAME:-OE4SI}"

# ── Initial Checks ──────────────────────────────────────────────────────────
if [[ -z "${CODEARTIFACT_API_KEY:-}" ]]; then
  echo -e "${RED}[error]${NC} Variable CODEARTIFACT_API_KEY undefined." >&2
  echo -e "        Example : ${CYAN}export CODEARTIFACT_API_KEY=\"your-api-key\"${NC}" >&2
  return 1 2>/dev/null
fi

if ! command -v curl &>/dev/null; then
  echo -e "${RED}[error]${NC} curl is required but not found. Use: apt-get install curl or brew install curl" >&2
  return 1 2>/dev/null
fi

if ! command -v jq &>/dev/null; then
  echo -e "${RED}[error]${NC} jq is required but not found. Use: apt install jq or brew install jq" >&2
  return 1 2>/dev/null
fi

if [[ "$TOKEN_ENDPOINT" == *"REPLACE_WITH_CDK_OUTPUT"* ]]; then
  if [[ -z "${CI:-}" ]]; then
    echo -e "${YELLOW}[warn]${NC} Variable TOKEN_ENDPOINT undefined." >&2
    echo -e "        Define this variable or edit this script to configure it." >&2
  fi
  return 1 2>/dev/null
fi

# ── Token Retrieval ─────────────────────────────────────────────────────────
if [[ -z "${CI:-}" ]]; then
  echo -e "${CYAN}[info]${NC}  Retrieval of the AWS CodeArtifact Token..."
fi

HTTP_CODE=$(curl -s -o /tmp/_ca_response.json -w "%{http_code}" \
  -H "x-api-key: ${CODEARTIFACT_API_KEY}" \
  "${TOKEN_ENDPOINT}")

if [[ "$HTTP_CODE" != "200" ]]; then
  echo -e "${RED}[error]${NC} The endpoint has returned the following response HTTP ${HTTP_CODE}." >&2
  cat /tmp/_ca_response.json 2>/dev/null && echo
  return 1 2>/dev/null
fi

TOKEN=$(jq -r '.token'      /tmp/_ca_response.json)
EXPIRATION=$(jq -r '.expiration' /tmp/_ca_response.json)
rm -f /tmp/_ca_response.json

if [[ -z "$TOKEN" || "$TOKEN" == "null" ]]; then
  echo -e "${RED}[error]${NC} The token is missing from the response" >&2
  return 1 2>/dev/null
fi

if [[ -z "${CI:-}" ]]; then
  echo -e "${GREEN}[ok]${NC}    CODEARTIFACT_TOKEN_${REPO_NAME} to export as an environment variable:"
  echo -e "${GREEN}[ok]${NC}    export CODEARTIFACT_TOKEN_${REPO_NAME}=\"$TOKEN\""

  # ── Maven ─────────────────────────────────────────────────────────────────────
  echo -e "        Configure your settings.xml with: <password>\${env.CODEARTIFACT_TOKEN_${REPO_NAME}}</password>"
  
  # ── NPM ───────────────────────────────────────────────────────────────────────
  echo -e "        Configure your .npmrc with: //${DOMAIN_ENDPOINT}/npm/${REPO_NAME}/:_authToken=\${CODEARTIFACT_TOKEN_${REPO_NAME}}"
  echo -e "        Configure your .npmrc with: @obeo:registry=https://${DOMAIN_ENDPOINT}/npm/${REPO_NAME}/"
  
  
  # ── Details ───────────────────────────────────────────────────────────────────
  echo -e "${GREEN}[ok]${NC}    The token will expire on: ${YELLOW}${EXPIRATION}${NC}"
else
  echo "$TOKEN"
fi
