#!/usr/bin/bash
#
# Suricatavel Agent CLI Wrapper
#
# This script provides a convenient way to invoke the Suricatavel Agent CLI
#
# Usage: suricatavel-agent [group] [action] [target] [options]
#
# Examples:
#   suricatavel-agent                        # Interactive mode
#   suricatavel-agent status                 # Show system status
#   suricatavel-agent version                # Show installed version
#   suricatavel-agent start                  # Start daemon
#   suricatavel-agent heartbeat              # Send on-demand heartbeat
#   suricatavel-agent positions status       # Check log reading positions
#   suricatavel-agent register --token=...   # Enroll agent with PKI
#

set -e

# Determine the script's real location (resolve symlinks)
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
    DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    SOURCE="$(readlink "$SOURCE")"
    [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

# Find the Suricatavel Agent application root
# Priority: 1) /var/opt/suricatavel-agent/current 2) /var/opt/suricatavel-agent 3) /usr/local/suricatavel-agent 4) relative to script location
if [ -f "/var/opt/suricatavel-agent/current/artisan" ]; then
    APP_DIR="/var/opt/suricatavel-agent/current"
elif [ -f "/var/opt/suricatavel-agent/artisan" ]; then
    APP_DIR="/var/opt/suricatavel-agent"
elif [ -f "/usr/local/suricatavel-agent/artisan" ]; then
    APP_DIR="/usr/local/suricatavel-agent"
elif [ -f "$SCRIPT_DIR/../../artisan" ]; then
    APP_DIR="$( cd "$SCRIPT_DIR/../.." && pwd )"
elif [ -f "$SCRIPT_DIR/../artisan" ]; then
    APP_DIR="$( cd "$SCRIPT_DIR/.." && pwd )"
else
    echo "Error: Could not find Suricatavel Agent application root" >&2
    exit 1
fi

# Capture the original working directory
export SURICATAVEL_AGENT_CWD="$(pwd)"

# Change to application directory
cd "$APP_DIR"

# Intercept --version / -V flag to invoke version command
if [ "$1" = "--version" ] || [ "$1" = "-V" ]; then
    exec php artisan suricatavel-agent version "${@:2}"
fi

# Execute the artisan command
exec php artisan suricatavel-agent "$@"