#!/bin/bash

# Name of the process
APP_NAME="hw-payment-api"
PID_FILE="/tmp/$APP_NAME.pid"
VENV_DIR="/var/www/html/hwPaymentPortal-be-dev/hw-payment-portal-api/venv"
GUNICORN_CMD="$VENV_DIR/bin/gunicorn -w 2 -k uvicorn.workers.UvicornWorker src.main:app --bind 0.0.0.0:8011"
LOG_FILE="/tmp/$APP_NAME.log"

start() {
    if [ -f "$PID_FILE" ]; then
        echo "$APP_NAME is already running."
    else
        echo "Starting $APP_NAME..."
        # Activate the virtual environment and run the app with gunicorn
        source $VENV_DIR/bin/activate
        $GUNICORN_CMD --pid $PID_FILE >> $LOG_FILE 2>&1 &
        echo "$APP_NAME started."
    fi
}

stop() {
    if [ -f "$PID_FILE" ]; then
        echo "Stopping $APP_NAME..."
        kill $(cat $PID_FILE)
        rm -f $PID_FILE
        echo "$APP_NAME stopped."
    else
        echo "$APP_NAME is not running."
    fi
}

restart() {
    stop
    start
}

status() {
    if [ -f "$PID_FILE" ]; then
        echo "$APP_NAME is running."
    else
        echo "$APP_NAME is not running."
    fi
}

view_logs() {
    if [ -f "$LOG_FILE" ]; then
        echo "Viewing logs for $APP_NAME:"
        tail -f $LOG_FILE
    else
        echo "No logs found. Make sure the app is running and logs are being generated."
    fi
}

# Check if the first argument is passed
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    logs)
        view_logs
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status|logs}"
        exit 1
        ;;
esac