#!/usr/bin/bash
#
# Drongo CLI Wrapper
#
# This script provides a convenient way to invoke the Drongo CLI
#
# Usage: drongo [group] [action] [target] [options]
#
# Examples:
#   drongo                        # Interactive mode
#   drongo status                 # Show system status
#   drongo version                # Show installed version
#   drongo ingest /path/eve.json   # Stream EVE JSON file
#   drongo rules list             # List synthesized rules
#   drongo timescale status       # Show TimescaleDB hypertables status
#

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 Drongo application root
# Priority: 1) /var/opt/drongo/current 2) /var/opt/drongo 3) relative to script location
if [ -f "/var/opt/drongo/current/artisan" ]; then
    APP_DIR="/var/opt/drongo/current"
elif [ -f "/var/opt/drongo/artisan" ]; then
    APP_DIR="/var/opt/drongo"
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 Drongo application root" >&2
    exit 1
fi

# Capture the original working directory
export DRONGO_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 drongo version "${@:2}"
fi

# Execute the artisan command
exec php artisan drongo "$@"
