#!/bin/bash

# Path to the c2 directory
c2dir="/home/blu/c2/stable/c2-patch"
InputMessageFile=~/Downloads/InputMessage.txt

# The way this would work, is that you would overwrite the InputMessage.txt on your server

# You can write a message by overwriting a the InputMessageFile file on the server
# How you do it is your choice.

# Start c2
echo "Starting Cultris II..."
sh "$c2dir/Linux-64-Start-cultris2.sh" > /dev/null 2>&1 &

# Instructions for the user
echo "Setup c2 - position your terminal where you can see and interact with it."
echo "This script will wait for you to type 'ready' when you are set up."
echo "----------------------------------"
sleep 1  # Brief pause for the user to read the message

# Wait for user confirmation
while true; do
    echo "Type 'ready' and press Enter to continue, or 'exit' to abort:"
    read -r moo

    if [ "$moo" = "ready" ]; then
        break  # Exit the loop if user is ready
    elif [ "$moo" = "exit" ]; then
        echo "Aborting..."
        exit  # Exit the script if user decides to abort
    else
        echo "Invalid input, please type 'ready' to proceed or 'exit' to abort."
    fi
done

# Main loop to process window interaction
while true; do
    # Check if the file exists and is not empty
    if [ -s $InputMessageFile ]; then
        InputMessage="$(cat $InputMessageFile)"
    else
        InputMessage=""
    fi

    # Get the window ID of the application
    WINDOW_ID=$(xdotool search --name "Cultris II" | head -1)
  
    # Ensure the window ID was found
    if [ -n "$WINDOW_ID" ]; then
        if [ -n "$InputMessage" ]; then
            # Output sending message
            echo "Sending: $InputMessage"
            
            # Send the external input
            xdotool type --delay 300 --window "$WINDOW_ID" "$InputMessage"
            xdotool key --delay 300 --window "$WINDOW_ID" Return

            # Clear the file after sending the input
            truncate -s 0 $InputMessageFile
        else
            # Default command to send if input is empty
            xdotool type --delay 300 --window "$WINDOW_ID" "/save"
            xdotool key --window "$WINDOW_ID" Return
        fi

        # Concatenate all chat log files if they exist
        chat_logs="$HOME/Cultris II chat log*"
        if compgen -G "$chat_logs" > /dev/null; then
            echo "Concatenating chat logs..."
            find "$HOME" -maxdepth 1 -name 'Cultris II chat log*' -print0 | sort -zr | xargs -0 tac > "$HOME/all_chat_logs.txt"
            echo "Clearing old chat logs..."
            find "$HOME" -maxdepth 1 -name 'Cultris II chat log*' -delete
        else
            echo "No chat logs to process."
        fi

        sleep 10  # Sleep to reduce CPU usage
    else
        echo "Could not find the Cultris II window. Please ensure the game is running and visible."
        sleep 10  # Wait before retrying to find the window
    fi
done
