#!/usr/bin/env bash
#
# endpoint-list.sh - List all Portainer endpoints/environments
#
# Usage: endpoint-list.sh [-f format]
#
# Environment variables:
#   PORTAINER_URL     - Portainer instance URL (e.g., https://portainer.example.com:9443)
#   PORTAINER_API_KEY - API access token
#
# Options:
#   -f format         Output format: table (default), json
#   -h                Show this help

set -euo pipefail

# Default values
FORMAT="table"

# Parse arguments
while getopts "f:h" opt; do
    case $opt in
        f) FORMAT="$OPTARG" ;;
        h)
            head -16 "$0" | grep "^#" | sed 's/^# \?//'
            exit 0
            ;;
        *)
            echo "Usage: $0 [-f format]" >&2
            exit 1
            ;;
    esac
done

# Validate environment
if [[ -z "${PORTAINER_URL:-}" ]]; then
    echo "Error: PORTAINER_URL environment variable not set" >&2
    exit 1
fi

if [[ -z "${PORTAINER_API_KEY:-}" ]]; then
    echo "Error: PORTAINER_API_KEY environment variable not set" >&2
    exit 1
fi

# Remove trailing slash from URL
PORTAINER_URL="${PORTAINER_URL%/}"

# TLS options
CURL_OPTS=()
if [ "${PORTAINER_INSECURE:-0}" = "1" ]; then
    CURL_OPTS+=(-k)
fi

# Fetch endpoints
response=$(curl -s "${CURL_OPTS[@]}" -w "\n%{http_code}" \
    -H "X-API-Key: ${PORTAINER_API_KEY}" \
    "${PORTAINER_URL}/api/endpoints")

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

if [[ "$http_code" != "200" ]]; then
    echo "Error: API request failed with status $http_code" >&2
    echo "$body" >&2
    exit 1
fi

# Output based on format
case "$FORMAT" in
    json)
        echo "$body" | jq '.'
        ;;
    table)
        echo "ID    NAME                          TYPE        STATUS    URL"
        echo "----  ----------------------------  ----------  --------  ---"
        echo "$body" | jq -r '.[] | [
            .Id,
            .Name,
            (if .Type == 1 then "docker" elif .Type == 2 then "agent" elif .Type == 3 then "azure" elif .Type == 4 then "edge" elif .Type == 5 then "kubernetes" else "unknown" end),
            (if .Status == 1 then "up" elif .Status == 2 then "down" else "unknown" end),
            .URL
        ] | @tsv' | while IFS=$'\t' read -r id name type status url; do
            printf "%-4s  %-28s  %-10s  %-8s  %s\n" "$id" "$name" "$type" "$status" "$url"
        done
        ;;
    *)
        echo "Error: Unknown format '$FORMAT'. Use: table, json" >&2
        exit 1
        ;;
esac
