#!/usr/bin/env bash
#
# session-init.sh — Initialize GLPI API session
#
# Usage: session-init.sh [-f] [-q]
#
# Authenticates with GLPI and caches the session token at
# ~/.cache/mosaic/glpi-session.
#
# Options:
#   -f    Force re-authentication (ignore cached session)
#   -q    Quiet mode — only output the session token
#   -h    Show this help
#
# Environment variables (or credentials.json):
#   GLPI_URL        — GLPI API base URL
#   GLPI_APP_TOKEN  — GLPI application token
#   GLPI_USER_TOKEN — GLPI user token
set -euo pipefail

MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"
load_credentials glpi

CACHE_DIR="$HOME/.cache/mosaic"
CACHE_FILE="$CACHE_DIR/glpi-session"
FORCE=false
QUIET=false

while getopts "fqh" opt; do
  case $opt in
    f) FORCE=true ;;
    q) QUIET=true ;;
    h) head -18 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
    *) echo "Usage: $0 [-f] [-q]" >&2; exit 1 ;;
  esac
done

# Check cached session validity
if [[ "$FORCE" == "false" ]] && [[ -f "$CACHE_FILE" ]]; then
  cached_token=$(cat "$CACHE_FILE")
  if [[ -n "$cached_token" ]]; then
    # Validate with a lightweight call
    http_code=$(curl -sk -o /dev/null -w "%{http_code}" \
      -H "App-Token: $GLPI_APP_TOKEN" \
      -H "Session-Token: $cached_token" \
      "${GLPI_URL}/getMyEntities")
    if [[ "$http_code" == "200" ]]; then
      [[ "$QUIET" == "false" ]] && echo "Using cached session (valid)" >&2
      echo "$cached_token"
      exit 0
    fi
    [[ "$QUIET" == "false" ]] && echo "Cached session expired, re-authenticating..." >&2
  fi
fi

# Initialize session
response=$(curl -sk -w "\n%{http_code}" \
  -H "App-Token: $GLPI_APP_TOKEN" \
  -H "Authorization: user_token $GLPI_USER_TOKEN" \
  "${GLPI_URL}/initSession")

http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [[ "$http_code" != "200" ]]; then
  echo "Error: Failed to initialize GLPI session (HTTP $http_code)" >&2
  echo "$body" | jq -r '.' 2>/dev/null >&2 || echo "$body" >&2
  exit 1
fi

session_token=$(echo "$body" | jq -r '.session_token // empty')

if [[ -z "$session_token" ]]; then
  echo "Error: No session_token in response" >&2
  exit 1
fi

# Cache the session
mkdir -p "$CACHE_DIR"
echo "$session_token" > "$CACHE_FILE"
chmod 600 "$CACHE_FILE"

[[ "$QUIET" == "false" ]] && echo "Session initialized and cached" >&2
echo "$session_token"
