#!/bin/bash

# DigiPoS AutoStart Script
# Ensures the application is running. Invoked via cron every 5 minutes.

SCRIPT_VERSION="1.0"
APP_NAME="pos_engine"
APP_DIR="/opt/digitory/$APP_NAME"
LOG_DIR="/var/log/digitory"
LOG_FILE="$LOG_DIR/autostart.log"
VERBOSE=false
[[ "$1" == "--verbose" ]] && VERBOSE=true

CMD_START="./bin/$APP_NAME daemon"
CMD_PID="./bin/$APP_NAME pid"

# Ensure log directory exists
mkdir -p "$LOG_DIR"

log() {
    ts=$(date "+%Y-%m-%d %H:%M:%S")
    echo "[$ts] $1" >> "$LOG_FILE"
}

# Checks if the application is running by validating the PID
is_running() {
    local pid
    pid=$($CMD_PID 2>/dev/null)

    if [[ -z "$pid" ]]; then
        return 1 # PID is empty
    fi

    if ps -p "$pid" >/dev/null 2>&1; then
        return 0 # Process exists
    else
        return 1 # Process does not exist
    fi
}

# Start the updated application and verify if it launched successfully
start_app() {
    log "🚀 Starting application..."
    if $CMD_START >> "$UPDATER_LOG" 2>&1; then
        pid=$($CMD_PID 2>/dev/null || true)
        if [[ -n "$pid" ]]; then
            log "✅ Application started. PID: $pid"
        else
            log "⚠️ Application start issued, but PID not found."
        fi
    else
        log "❌ Failed to start application."
        exit 1
    fi
}


# Main logic
main() {
    $VERBOSE && log "🔄 Autostart check started $SCRIPT_VERSION"
    
    cd "$APP_DIR" || {
        log "❌ Failed to cd into $APP_DIR"
        exit 1
    }

    $VERBOSE && echo "[$(date)] 🔄 Autostart check initiated"

    if is_running; then
        $VERBOSE && echo "[$(date)] ✅ Application is already running."
        exit 0
    fi

    echo "[$(date)] ⚠️  Application not running. Attempting to start..."
    start_app
} 

main "$@"

