#!/bin/bash
#
# pause-all - Pause all players using the audiocontrol API
#
# Usage: pause-all [PLAYER_NAME_OR_ID]
#
# This script calls the audiocontrol API to pause all players.
# Optionally, you can specify a player name, ID, or alias to exclude from the pause operation.
# Supported aliases: mpd, spotify/spotifyd/librespot, raat/roon, shairport/airplay/shairport-sync, lms/squeezelite
#
# Examples:
#   pause-all                    # Pause all players
#   pause-all spotify            # Pause all players except the one named "spotify"
#   pause-all librespot          # Pause all players except Spotify (using alias)
#   pause-all mpd:localhost:6600 # Pause all except MPD with this ID
#

# Default API endpoint - can be overridden with environment variable
API_BASE_URL="${AUDIOCONTROL_API_URL:-http://localhost:1080/api}"

# Function to display usage information
usage() {
    echo "Usage: $0 [PLAYER_NAME_OR_ID]"
    echo ""
    echo "Pause all players using the audiocontrol API."
    echo ""
    echo "ARGUMENTS:"
    echo "  PLAYER_NAME_OR_ID       Exclude the specified player from the pause operation"
    echo "                          Can be player name, ID, or alias (mpd, spotify/spotifyd/librespot,"
    echo "                          raat/roon, shairport/airplay/shairport-sync, lms/squeezelite)"
    echo ""
    echo "ENVIRONMENT VARIABLES:"
    echo "  AUDIOCONTROL_API_URL    Base URL for the audiocontrol API (default: http://localhost:1080/api)"
    echo ""
    echo "EXAMPLES:"
    echo "  $0                      Pause all players"
    echo "  $0 spotify              Pause all players except 'spotify'"
    echo "  $0 librespot            Pause all players except Spotify (using alias)"
    echo "  $0 mpd:localhost:6600   Pause all except MPD with this ID"
    exit 1
}

# Check for help flag
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    usage
fi

# Parse command line arguments
EXCEPT_PLAYER=""
if [[ -n "$1" && "$1" != "-h" && "$1" != "--help" ]]; then
    EXCEPT_PLAYER="$1"
elif [[ "$1" == "-h" || "$1" == "--help" ]]; then
    usage
elif [[ $# -gt 1 ]]; then
    echo "Error: Too many arguments. Only one player name/ID is allowed."
    usage
fi

# Build the API URL
API_URL="${API_BASE_URL}/players/pause-all"
if [[ -n "$EXCEPT_PLAYER" ]]; then
    # URL-encode the except parameter
    ENCODED_EXCEPT=$(printf '%s' "$EXCEPT_PLAYER" | sed 's/ /%20/g; s/:/%3A/g')
    API_URL="${API_URL}?except=${ENCODED_EXCEPT}"
fi

# Check if curl is available
if ! command -v curl &> /dev/null; then
    echo "Error: curl is required but not installed"
    exit 1
fi

# Make the API call
echo "Calling audiocontrol API: $API_URL"
RESPONSE=$(curl --max-time 2 --connect-timeout 2 -s -X POST "$API_URL" -H "Content-Type: application/json")
CURL_EXIT_CODE=$?

# Check if curl succeeded
if [[ $CURL_EXIT_CODE -ne 0 ]]; then
    echo "Error: Failed to connect to audiocontrol API at $API_URL"
    echo "Make sure audiocontrol is running and accessible at $API_BASE_URL"
    exit 1
fi

# Parse the JSON response to extract success and message
if command -v jq &> /dev/null; then
    # Use jq if available for proper JSON parsing
    SUCCESS=$(echo "$RESPONSE" | jq -r '.success // false')
    MESSAGE=$(echo "$RESPONSE" | jq -r '.message // "No message"')
else
    # Fallback to basic text processing if jq is not available
    SUCCESS=$(echo "$RESPONSE" | grep -o '"success":[^,}]*' | cut -d':' -f2 | tr -d ' "')
    MESSAGE=$(echo "$RESPONSE" | grep -o '"message":"[^"]*"' | cut -d':' -f2- | sed 's/^"//; s/"$//')
fi

# Display the result
if [[ "$SUCCESS" == "true" ]]; then
    echo "Success: $MESSAGE"
    exit 0
else
    echo "Failed: $MESSAGE"
    echo "Raw response: $RESPONSE"
    exit 1
fi