#!/bin/bash

read -p "Username: " USERNAME </dev/tty
read -s -p "Password: " PASS </dev/tty
echo
echo "Snapshot test — just testing authentication"

# Create JSON payload safely
payload=$(jq -n --arg u "$USERNAME" --arg p "$PASS" '{Username:$u, Password:$p}')

echo "-----------------------------"
echo "DEBUG: Generated payload:"
echo "$payload"
echo "-----------------------------"

# Run HTTP request with verbose output
echo "DEBUG: Executing HTTP request..."
JWT=$(httpie.http --ignore-stdin POST :9000/api/auth \
    Content-Type:application/json \
    <<< "{\"Username\":\"${USERNAME}\",\"Password\":\"${PASS}\"}" | jq -r ".jwt")

if [ "null" = "${JWT}" ] || [ -z "${JWT}" ]; then
    echo "Invalid credentials for Portainer account"
    exit 1
fi

