#!/bin/bash
# snapshotSSL.sh: Fetch and apply a snapshot to the Helmut4 Portainer stack

set -euo pipefail

# Validate arguments
SNAPSHOT_VERSION="${1:-}"
if [[ -z "$SNAPSHOT_VERSION" ]]; then
  echo "Error: please provide a snapshot version" >&2
  exit 1
fi

# Load OS info (optional)
. /etc/os-release 2>/dev/null || true

# Determine Portainer base URL (9443 HTTPS or 9000 HTTP)
if http --timeout=5 --verify=no GET https://localhost:9443/api/status >/dev/null 2>&1; then
  BASE_URL="https://localhost:9443"
elif http --timeout=5 GET http://localhost:9000/api/status >/dev/null 2>&1; then
  BASE_URL="http://localhost:9000"
else
  echo "❌ Portainer not reachable on 9443 or 9000" >&2
  exit 1
fi
echo "✅ Portainer is at $BASE_URL" >&2

# Ensure PASS is defined (may come from environment)
PASS="${PASS:-}"

# --- DEBUG: show PASS (may contain sensitive data!) ---
echo "+ DEBUG: PASS='$PASS'" >&2

# Authenticate and get JWT, capturing raw response
set +e
RAW_AUTH=$(http --ignore-stdin --verify=no POST "$BASE_URL/api/auth" \
  Username="admin" Password="$PASS")
AUTH_EXIT=$?
set -e

echo "+ DEBUG: HTTPie exit code for auth = $AUTH_EXIT" >&2
echo "+ DEBUG: raw auth response:" >&2
echo "$RAW_AUTH" | sed 's/^/    /' >&2

if [ "$AUTH_EXIT" -ne 0 ]; then
  echo "❌ Auth request failed (exit $AUTH_EXIT)" >&2
  exit 1
fi

# Try to parse JWT
set +e
JWT=$(echo "$RAW_AUTH" | jq -r .jwt)
JQ_EXIT=$?
set -e

echo "+ DEBUG: jq exit code for .jwt = $JQ_EXIT" >&2
echo "+ DEBUG: JWT='$JWT'" >&2

if [ "$JQ_EXIT" -ne 0 ] || [[ -z "$JWT" ]] || [[ "$JWT" == "null" ]]; then
  echo "❌ Authentication failed or returned invalid JSON" >&2
  exit 1
fi

echo "✅ Authenticated, received JWT" >&2

# Fetch stacks and locate Helmut4
STACKS=$(http --ignore-stdin --verify=no GET "$BASE_URL/api/stacks" \
  Authorization:"Bearer $JWT")
if ! echo "$STACKS" | jq . >/dev/null 2>&1; then
  echo "❌ /api/stacks did not return JSON, got:" >&2
  echo "$STACKS" >&2
  exit 1
fi

STACK=""
while IFS= read -r row; do
  _jq() { echo "$row" | base64 --decode | jq -r "$1"; }
  name=$(_jq '.Name')
  if [[ "${name,,}" == "helmut4" ]]; then
    STACK=$(_jq '.Id')
    break
  fi
done < <(echo "$STACKS" | jq -r '.[] | @base64')

if [[ -z "$STACK" ]]; then
  echo "❌ Helmut4 stack not found" >&2
  exit 1
fi
echo "✅ Helmut4 Stack found with Id: $STACK" >&2

# Grab current compose file
RAW_CONTENT=$(http --ignore-stdin --verify=no GET "$BASE_URL/api/stacks/$STACK/file" \
  Authorization:"Bearer $JWT")
if ! echo "$RAW_CONTENT" | jq . >/dev/null 2>&1; then
  echo "❌ /api/stacks/$STACK/file did not return JSON:" >&2
  echo "$RAW_CONTENT" >&2
  exit 1
fi
CONTENT=$(echo "$RAW_CONTENT" | jq -r .StackFileContent)

# Download snapshot manifest
echo "Fetching snapshot manifest $SNAPSHOT_VERSION..." >&2
SNAPSHOT=$(curl --fail --show-error --silent \
  "https://repo.moovit24.de/install/snapshots/$SNAPSHOT_VERSION")
if [[ -z "$SNAPSHOT" ]]; then
  echo "Error: could not get snapshot $SNAPSHOT_VERSION" >&2
  exit 1
elif [[ "$SNAPSHOT" == *"<html>"* ]]; then
  echo "Error grabbing snapshot manifest:" >&2
  echo "$SNAPSHOT" >&2
  exit 1
fi
echo "✅ Snapshot manifest loaded" >&2

# (rest of your script unchanged…)
# Perform license migration check, apply updates, redeploy, etc.

echo "✅ Update done" >&2

