#!/usr/bin/env bash
#
# stack-stop.sh - Stop a running Portainer stack
#
# Usage: stack-stop.sh -n <stack-name>
#
# Environment variables:
#   PORTAINER_URL     - Portainer instance URL (e.g., https://portainer.example.com:9443)
#   PORTAINER_API_KEY - API access token
#
# Options:
#   -n name           Stack name (required)
#   -i id             Stack ID (alternative to -n)
#   -h                Show this help

set -euo pipefail

# Default values
STACK_NAME=""
STACK_ID=""

# Parse arguments
while getopts "n:i:h" opt; do
    case $opt in
        n) STACK_NAME="$OPTARG" ;;
        i) STACK_ID="$OPTARG" ;;
        h)
            head -16 "$0" | grep "^#" | sed 's/^# \?//'
            exit 0
            ;;
        *)
            echo "Usage: $0 -n <stack-name>" >&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

if [[ -z "$STACK_NAME" && -z "$STACK_ID" ]]; then
    echo "Error: Either -n <stack-name> or -i <stack-id> is required" >&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

# Function to make API requests
api_request() {
    local method="$1"
    local endpoint="$2"

    curl -s "${CURL_OPTS[@]}" -w "\n%{http_code}" -X "$method" \
        -H "X-API-Key: ${PORTAINER_API_KEY}" \
        "${PORTAINER_URL}${endpoint}"
}

# Get stack info by name
if [[ -n "$STACK_NAME" ]]; then
    response=$(api_request GET "/api/stacks")
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [[ "$http_code" != "200" ]]; then
        echo "Error: Failed to list stacks (HTTP $http_code)" >&2
        exit 1
    fi

    stack_info=$(echo "$body" | jq --arg name "$STACK_NAME" '.[] | select(.Name == $name)')

    if [[ -z "$stack_info" || "$stack_info" == "null" ]]; then
        echo "Error: Stack '$STACK_NAME' not found" >&2
        exit 1
    fi

    STACK_ID=$(echo "$stack_info" | jq -r '.Id')
    ENDPOINT_ID=$(echo "$stack_info" | jq -r '.EndpointId')
else
    response=$(api_request GET "/api/stacks/${STACK_ID}")
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [[ "$http_code" != "200" ]]; then
        echo "Error: Failed to get stack (HTTP $http_code)" >&2
        exit 1
    fi

    stack_info="$body"
    STACK_NAME=$(echo "$stack_info" | jq -r '.Name')
    ENDPOINT_ID=$(echo "$stack_info" | jq -r '.EndpointId')
fi

echo "Stopping stack '$STACK_NAME' (ID: $STACK_ID)..."

response=$(api_request POST "/api/stacks/${STACK_ID}/stop?endpointId=${ENDPOINT_ID}")
http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [[ "$http_code" == "200" ]]; then
    echo "Successfully stopped stack '$STACK_NAME'"
else
    echo "Error: Failed to stop stack (HTTP $http_code)" >&2
    echo "$body" | jq '.' 2>/dev/null || echo "$body" >&2
    exit 1
fi
