#!/bin/bash
# Get API token for lavtomate via Kerberos authentication
#
# Usage:
#   lavtomate-get-token [TTL] [DESCRIPTION]
#
# Arguments:
#   TTL          Token lifetime: "8h" (hours), "7d" (days), or seconds (default: "8h")
#   DESCRIPTION  Token description (default: "ssh-session-HOSTNAME-DATE")
#
# Token caching:
#   Tokens are cached in ~/.cache/lavtomate/ by TTL+description hash.
#   A cached token is reused if it has not expired (based on file age).
#   Use LAVTOMATE_NO_CACHE=1 to force creating a new token.
#
# Example:
#   lavtomate-get-token              # 8-hour token, auto description
#   lavtomate-get-token 7d           # 7-day token
#   lavtomate-get-token 1h "CI job"  # 1-hour token with description

set -e

TTL="${1:-8h}"
DESC="${2:-ssh-session-$(hostname -s)-$(date +%Y%m%d)}"

# Lavtomate server URL (can be overridden via environment)
LAVTOMATE_URL="${LAVTOMATE_URL:-https://lavtomate.office.etersoft.ru}"

# Convert TTL to seconds for cache expiry check
ttl_to_seconds() {
    local ttl="$1"
    case "$ttl" in
        *d) echo $(( ${ttl%d} * 86400 )) ;;
        *h) echo $(( ${ttl%h} * 3600 )) ;;
        *m) echo $(( ${ttl%m} * 60 )) ;;
        *)  echo "$ttl" ;;
    esac
}

TTL_SECONDS=$(ttl_to_seconds "$TTL")

# Cache directory and key
CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/lavtomate"
CACHE_KEY=$(echo "${LAVTOMATE_URL}:${DESC}" | md5sum | cut -d' ' -f1)
CACHE_FILE="$CACHE_DIR/$CACHE_KEY"

# Check cached token (unless LAVTOMATE_NO_CACHE=1)
if [ "$LAVTOMATE_NO_CACHE" != "1" ] && [ -f "$CACHE_FILE" ]; then
    # Check if token has not expired (file age < TTL with 60s safety margin)
    file_age=$(( $(date +%s) - $(stat -c %Y "$CACHE_FILE") ))
    max_age=$(( TTL_SECONDS - 60 ))
    [ "$max_age" -lt 60 ] && max_age=60
    if [ "$file_age" -lt "$max_age" ]; then
        cat "$CACHE_FILE"
        exit 0
    fi
fi

# Create token via Kerberos-authenticated request
response=$(curl -s --negotiate -u : \
    -X POST "${LAVTOMATE_URL}/api/auth/api-keys" \
    -H "Content-Type: application/json" \
    -d "{\"description\": \"${DESC}\", \"ttl\": \"${TTL}\"}")

# Check for errors (FastAPI uses "detail", Flask uses "error")
if echo "$response" | grep -qE '"error"|"detail"'; then
    echo "Error: $(echo "$response" | jq -r '.detail // .error // "Unknown error"')" >&2
    exit 1
fi

# Extract the token
token=$(echo "$response" | jq -r '.api_key // empty')

if [ -z "$token" ]; then
    echo "Error: Failed to extract token from response" >&2
    echo "Response: $response" >&2
    exit 1
fi

# Cache the token
mkdir -p "$CACHE_DIR"
echo -n "$token" > "$CACHE_FILE"
chmod 600 "$CACHE_FILE"

echo "$token"
