#!/bin/bash
# Ring2All Command Line Utility (r2a_cmd)
# Wrapper for API CLI

export NODE_ENV=production

# Resolve the directory where the script is located to find project root
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do 
  DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" 
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"

# Expected: .../apps/api/scripts/r2a_cmd -> API_DIR is parent
API_DIR="$(dirname "$SCRIPT_DIR")"

# Validate directory
if [ ! -f "$API_DIR/package.json" ]; then
    # Fallback to standard installation path
    API_DIR="/var/www/softswitch/apps/api"
fi

if [ ! -d "$API_DIR" ]; then
    echo "Error: API directory not found at $API_DIR"
    exit 1
fi

# Execute CLI script
cd "$API_DIR"

if [ -f "dist/cli/index.js" ]; then
    node dist/cli/index.js "$@"
else
    echo "Error: Compiled CLI not found at $API_DIR/dist/cli/index.js"
    echo "Please ensure the API project is built (npm run build)."
    exit 1
fi
