#!/bin/bash

service_running=false 
while true; do
    cd /home/ubuntu/go/ssp/go-ssp-qa/ssp-main &&
    
    go build main.go 2>&1 | tee -a /opt/script.log  # Capture compilation output
    compile_return_code=$?

    if [ $compile_return_code -eq 0 ]; then
        # Only start the service if it's not already running
        if [ "$service_running" = false ]; then
            ./main &
            main_pid=$!  # Capture the PID of the background process

            sleep 5  # Allow some time for the program to start

            # Check if the process is still running
            if ps -p $main_pid > /dev/null; then
                service_running=true  # Update the service status
            fi
        fi
    fi

    # Check if the process is not running
    if [ "$service_running" = true ] && ! ps -p $main_pid > /dev/null; then
        echo "Service has stopped unexpectedly. Restarting..."
        ./main &  # Restart the service
        main_pid=$!  # Capture the PID of the background process
        sleep 5  # Allow some time for the program to start

        # Check if the process is still running
        if ps -p $main_pid > /dev/null; then
            service_running=true  # Update the service status
        fi
    fi

    sleep 15
done

