#!/bin/bash

WATCH_DIR="/run/task-trigger"
LOG_FILE="/tmp/trigger.log"

handle_git_task() {
    local REPO_DIR="$1"
    local REF="$2"

    echo "📁 Switching to $REPO_DIR" >> "$LOG_FILE"
    cd "$REPO_DIR" || {
        echo "❌ Failed to cd into $REPO_DIR" >> "$LOG_FILE"
        return 1
    }

    echo "🔄 Fetching latest refs..." >> "$LOG_FILE"
    git fetch --all >> "$LOG_FILE" 2>&1

    if git rev-parse --verify --quiet "origin/$REF" >/dev/null; then
        echo "🌿 Switching to branch: $REF" >> "$LOG_FILE"
        git checkout "$REF" >> "$LOG_FILE" 2>&1
        git pull origin "$REF" >> "$LOG_FILE" 2>&1
    elif git rev-parse --verify --quiet "refs/tags/$REF" >/dev/null; then
        echo "🏷️ Checking out tag: $REF" >> "$LOG_FILE"
        git checkout "tags/$REF" >> "$LOG_FILE" 2>&1
    else
        echo "❌ Invalid branch or tag: $REF" >> "$LOG_FILE"
        return 1
    fi
}

stop_services() {
	echo "⛔ Stopping Service-V2..." >> "$LOG_FILE"
	systemctl stop coral-services-v2.service >> "$LOG_FILE" 2>&1
	echo "⛔ Stopping Telemetry..." >> "$LOG_FILE"
	systemctl stop coral-telemetry.service >> "$LOG_FILE" 2>&1
	echo "⛔ Stopping Postgres..." >> "$LOG_FILE"
	systemctl stop postgresql@12-main.service
	sleep 5
}

start_services() {
	sleep 10
	echo "▶️ Starting Postgres..." >> "$LOG_FILE"
	systemctl start postgresql@12-main.service
	sleep 10
	echo "▶️ Starting Service-V2..." >> "$LOG_FILE"
	systemctl start coral-services-v2.service >> "$LOG_FILE" 2>&1
	sleep 10
	echo "▶️ Starting Telemetry..." >> "$LOG_FILE"
	systemctl start coral-telemetry.service >> "$LOG_FILE" 2>&1
}

clean_git() {
    echo "🔁 Switching back to master..." >> "$LOG_FILE"
    git checkout master >> "$LOG_FILE" 2>&1
    git pull origin master >> "$LOG_FILE" 2>&1

    echo "🗑️ Cleaning up local branches..." >> "$LOG_FILE"
    for branch in $(git for-each-ref --format='%(refname:short)' refs/heads/ | grep -v '^master$'); do
        git branch -D "$branch" >> "$LOG_FILE" 2>&1
    done

    echo "✅ Task complete for $REF" >> "$LOG_FILE"

    pkill -f build-logs
}

mvn_build() {
	echo "🧹 Running Maven clean and package..." >> "$LOG_FILE"
    mvn clean >> "$LOG_FILE" 2>&1
    mvn package >> "$LOG_FILE" 2>&1
}

react_build() {
	echo "🧹 Running React clean and package..." >> "$LOG_FILE"

	rm -rf build/
	npm install --legacy-peer-deps >> "$LOG_FILE"
	NODE_OPTIONS="--max-old-space-size=4096" npm run build >> "$LOG_FILE"
}

mkdir "$WATCH_DIR"
chmod -R 777 "$WATCH_DIR"

rm -f -- "$WATCH_DIR/service-v2"
rm -f -- "$WATCH_DIR/telemetry"
rm -f -- "$WATCH_DIR/gui"
rm -f -- "$WATCH_DIR/config"
rm -f -- "$WATCH_DIR/db-init"
rm -f -- "$WATCH_DIR/db-backup"
rm -f -- "$WATCH_DIR/update-config"
rm -f -- "$WATCH_DIR/execute-command"

inotifywait -mq -e create "$WATCH_DIR" | while read -r path action file; do
    echo "🔔 Triggered by: $file" >> "$LOG_FILE"

    case "$file" in
        service-v2)
	    # Read branch or tag from file content
		stop_services
    	REF=$(cat "$path/$file" | tr -d '\r\n')

		handle_git_task "/usr/src/services-app" "$REF"
	    mvn_build

	    cp /usr/src/services-app/target/services-v2.jar /opt/service-v2/services-v2.jar

	    start_services

	    clean_git

        ;;

        telemetry)
		# Read branch or tag from file content
		stop_services
    	REF=$(cat "$path/$file" | tr -d '\r\n')

	    handle_git_task "/usr/src/telemetry" "$REF"
	    mvn_build

	    cp /usr/src/telemetry/target/telemetry-*.jar /opt/telemetry/telemetry.jar

	    start_services
	    clean_git

        ;;
        
        config)
	    # Read branch or tag from file content
		stop_services
        REF=$(cat "$path/$file" | tr -d '\r\n')

	    handle_git_task "/usr/src/com.coraltele.config" "$REF"
	    mvn_build

	    echo "🧹 Running make clean..." >> "$LOG_FILE"
	    make clean >> "$LOG_FILE" 2>&1

	    echo "🧼 Running make tidy..." >> "$LOG_FILE"
	    make tidy >> "$LOG_FILE" 2>&1

	    echo "🔨 Running make build..." >> "$LOG_FILE"
	    make build >> "$LOG_FILE" 2>&1

	    cp /usr/src/com.coraltele.config/target/config-*.jar /opt/config/config.jar
	    cp /usr/src/com.coraltele.config/build/update-config /opt/config/update-config
		cp /usr/src/com.coraltele.config/build/extension /opt/config/extension
		cp /usr/src/com.coraltele.config/build/fax /opt/config/fax
		cp /usr/src/com.coraltele.config/build/logs /usr/local/bin/logs

	    cp /usr/src/com.coraltele.config/src/main/resources/coral.default.ini /opt/config/coral.default.ini
	    cp /usr/src/com.coraltele.config/src/main/resources/inotify-task-watcher /opt/config/inotify-task-watcher

	    chmod +x /opt/config/inotify-task-watcher
	    chmod +x /opt/config/update-config
		chmod +x /opt/config/extension
	    chmod +x /opt/config/fax
		chmod +x /usr/local/bin/logs

		mkdir -p /opt/config/completion

		/opt/config/extension completion zsh > /opt/config/completion/extension
		/opt/config/fax completion zsh > /opt/config/completion/fax
		/usr/local/bin/logs completion zsh > /opt/config/completion/logs

		start_services
	    clean_git
	    systemctl restart task-watcher.service


        ;;

        gui)
		stop_services
	    # Read branch or tag from file content
        REF=$(cat "$path/$file" | tr -d '\r\n')

	    handle_git_task "/usr/src/gui" "$REF"
	    react_build
		start_services

	    /bin/bash -c "rm -rf /var/www/html"
	    rm -rf /var/www/html
	    mv /usr/src/gui/build/html /var/www
	    clean_git

        ;;

	    db-init)
		stop_services
        REF=$(cat "$path/$file" | tr -d '\r\n')
	    echo "🔔 Triggered by: $REF" >> "$LOG_FILE"

    	echo "🧹 Cleaning PostgreSQL data directory..." >> "$LOG_FILE"
    	/bin/bash -c "rm -rf /var/lib/postgresql/12/main/*" >> "$LOG_FILE" 2>&1

    	echo "🔄 Initializing new PostgreSQL cluster..." >> "$LOG_FILE"
    	su - postgres -c "/usr/lib/postgresql/12/bin/initdb -D /var/lib/postgresql/12/main" >> "$LOG_FILE" 2>&1

    	echo "▶️ Starting PostgreSQL..." >> "$LOG_FILE"
    	systemctl start postgresql >> "$LOG_FILE" 2>&1

		FOLDER="/usr/data/$REF"


		echo "🔧 Starting PostgreSQL database creation..." >> "$LOG_FILE"

		for db in billing coralapps switch telemetry users jobs; do
  			echo "📦 Creating database: $db" >> "$LOG_FILE"
  			psql -U postgres -h 127.0.0.1 -c "CREATE DATABASE $db;" >> "$LOG_FILE" 2>&1
		done

		echo "✅ Database creation complete." >> "$LOG_FILE"

		echo "🔁 Starting data restoration from $FOLDER..." >> "$LOG_FILE"

		for db in switch billing coralapps telemetry users jobs; do
  			FILE="$FOLDER/$db.db"
  			echo "📥 Restoring $FILE into database: $db" >> "$LOG_FILE"
  			pg_restore -U postgres -h 127.0.0.1 -d "$db" "$FILE" >> "$LOG_FILE" 2>&1
		done

		echo "✅ All databases restored successfully." >> "$LOG_FILE"

    	echo "✅ PostgreSQL reinitialization complete." >> "$LOG_FILE"

		start_services

		pkill -f build-logs

        ;;

	    db-backup)
        REF=$(cat "$path/$file" | tr -d '\r\n')
	    echo "🔔 Triggered by: $REF" >> "$LOG_FILE"

		FOLDER="/usr/data/$REF"
    		/bin/bash -c "rm -rf $FOLDER" >> "$LOG_FILE" 2>&1

		mkdir -p "$FOLDER"

		echo "🔁 Starting PostgreSQL backup to $FOLDER (format: custom -Fc)" >> "$LOG_FILE"

		for db in billing coralapps switch telemetry users jobs; do
  			OUT_FILE="$FOLDER/${db}.db"
  			echo "📦 Dumping database: $db -> $OUT_FILE" >> "$LOG_FILE"
  			pg_dump -U postgres -h 127.0.0.1 -Fc "$db" -f "$OUT_FILE"

  			if [ $? -eq 0 ]; then
    				echo "✅ Successfully backed up: $db" >> "$LOG_FILE"
  			else
    				echo "❌ Failed to back up: $db" >> "$LOG_FILE"
  			fi
		done

		echo "✅ All backups completed." >> "$LOG_FILE"

		pkill -f build-logs
	   
        ;;

   	    update-config)
		echo "🔧 Update Configuration Triggered" >> "$LOG_FILE"

		stop_services

		readarray -t lines < "$path/$file"

		CONFIG_SECTION="${lines[0]}"
		CONFIG_PROPERTY="${lines[1]}"
		CONFIG_VALUE="${lines[2]}"

		echo "📁 Section     : $CONFIG_SECTION" >> "$LOG_FILE"
		echo "🔑 Property    : $CONFIG_PROPERTY" >> "$LOG_FILE"
		echo "✏️  Value       : $CONFIG_VALUE" >> "$LOG_FILE"
		echo "🚀 Running update-config..." >> "$LOG_FILE"

		/opt/config/update-config "$CONFIG_SECTION" "$CONFIG_PROPERTY" "$CONFIG_VALUE" >> "$LOG_FILE" 2>&1

		start_services

	  	pkill -f build-logs

	    ;;

		execute-command)
		echo "🔧 Execute Command Triggered" >> "$LOG_FILE"
		readarray -t lines < "$path/$file"

		case "${lines[0]}" in
			"logs")
				echo "🔁 Restarting services..." >> "$LOG_FILE"
				;;
			*)
				echo "⚠️ Unknown command: ${lines[0]}" >> "$LOG_FILE"
				;;
		esac
		;;

        *)
        echo "⚠️ Unknown trigger: $file" >> /var/log/task-exec.log
        ;;
    esac

    rm -f "$path/$file"
done