#!/bin/bash
# =====================================================
# start.sh — Start the Niscom Payroll backend
# =====================================================

DEPLOY_DIR=/home3/webniscom/payroll
JAR=$DEPLOY_DIR/payroll.jar
PID_FILE=$DEPLOY_DIR/payroll.pid
LOG_FILE=$DEPLOY_DIR/payroll.log
CONFIG=$DEPLOY_DIR/application.properties

# Check if already running
if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if kill -0 "$PID" 2>/dev/null; then
        echo "Already running with PID $PID"
        echo "Run stop.sh first if you want to restart"
        exit 1
    fi
fi

# Check JAR exists
if [ ! -f "$JAR" ]; then
    echo "ERROR: payroll.jar not found at $JAR"
    exit 1
fi

# Check Java
if ! command -v java &> /dev/null; then
    echo "ERROR: Java is not installed or not in PATH"
    exit 1
fi

echo "Starting Niscom Payroll backend..."
cd "$DEPLOY_DIR"

nohup java -jar "$JAR" \
    --spring.config.location="$CONFIG" \
    > "$LOG_FILE" 2>&1 &

echo $! > "$PID_FILE"
echo "Started with PID $(cat $PID_FILE)"
echo "Logs: tail -f $LOG_FILE"
echo "Waiting for startup..."

# Wait up to 30s for the app to start
for i in {1..30}; do
    sleep 1
    if curl -s http://localhost:8080/api/payslip/ping > /dev/null 2>&1; then
        echo "✓ Backend is up and running on port 8080"
        exit 0
    fi
    echo -n "."
done

echo ""
echo "App is taking longer than expected. Check logs:"
echo "tail -f $LOG_FILE"
