#!/bin/bash

IN="sms_backend"

log="/var/log"
pid="/var/run"

export GOPATH=/var/www/html/gocode/src
export PATH=$PATH:/var/www/html/gocode/src/sms_api/
export GOOGLE_APPLICATION_CREDENTIALS="/var/www/html/gocode/src/service.json"

BOOTSTRAP_SERVER="bootstrap.sms-kafka.asia-south1.managedkafka.multitv-gcp.cloud.goog:9092"

arr=$(echo $IN | tr ";" "\n")
dt=$(date '+%d-%m-%YT%H:%M:%S')

red='\033[0;31m'
green='\033[0;32m'
NC='\033[0m'

if [ $# -ne 1 ]; then
    echo "Wrong number of arguments"
    exit 1
fi

for x in $arr
do

    # ================= START =================
    if [ "$1" == "start" ]; then

        if [ -f "$pid/$x.pid" ] && kill -0 $(cat "$pid/$x.pid") 2>/dev/null; then
            echo -e "${red}$x ${green}is already running${NC}"
            continue
        fi

        echo -e "${red}Starting Process${NC} -> ${green}$x${NC}"

        cd /var/www/html/gocode/src/sms_api || exit 1

        ./"$x" >> "$log/$x.log" 2>&1 &

        echo $! > "$pid/$x.pid"


    # ================= STOP =================
    elif [ "$1" == "stop" ]; then

        if [ -f "$pid/$x.pid" ]; then
            subsys_pid=$(cat "$pid/$x.pid")

            echo -e "${red}Stopping Process${NC} -> ${green}$x:$subsys_pid${NC}"

            kill "$subsys_pid" 2>/dev/null

            rm -f "$pid/$x.pid"
        else
            echo -e "${red}$x${NC}:${green}Not running${NC}"
        fi


    # ================= STATUS =================
    elif [ "$1" == "status" ]; then

        if [ -f "$pid/$x.pid" ]; then
            subsys_pid=$(cat "$pid/$x.pid")
            echo -e "${red}$x${NC}:${green}$subsys_pid${NC}"
        else
            echo -e "${red}$x${NC}:${green}Not running${NC}"
        fi


    # ================= KAFKA TOPICS (NEW ADDED) =================
    elif [ "$1" == "kafka-topics" ]; then

        echo "🚀 Connecting to GCP Managed Kafka..."
        echo "📡 Bootstrap: $BOOTSTRAP_SERVER"

        export CLASSPATH="/opt/kafka/libs/*:/opt/gcp-auth/google-hosted-kafka-authenticator-1.0.5-all.jar"

        cat > client.properties <<EOF
security.protocol=SASL_SSL
sasl.mechanism=OAUTHBEARER
sasl.login.callback.handler.class=com.google.cloud.hosted.kafka.auth.GcpLoginCallbackHandler
sasl.jaas.config=org.apache.kafka.common.security.oauthbearer.OAuthBearerLoginModule required;
ssl.endpoint.identification.algorithm=https
EOF

        echo "📋 Listing Kafka Topics..."

        /opt/kafka/bin/kafka-topics.sh \
            --bootstrap-server "$BOOTSTRAP_SERVER" \
            --command-config client.properties \
            --list

        echo "✅ Done"


    # ================= HELP =================
    elif [ "$1" == "help" ]; then

        echo "start         - Start system"
        echo "stop          - Stop system"
        echo "status        - Check status"
        echo "kafka-topics  - List Kafka topics"

    else
        echo "Wrong argument. Use help."
        exit 1
    fi

done
