#!/bin/bash
#

set -e  #  Exit immediately if any command exits with a non-zero status

check_venv() {  # Check if the venv module is available
    if python3 -c "import venv" &> /dev/null; then
        return 0
    else
        echo "The 'venv' module is not available. If using Debian, be sure to install python3-venv."
        return 1
    fi
}

create_venv() {
    python3 -m venv env
}

activate_venv() {
    source env/bin/activate
}

install_dependencies() {
    pip install --upgrade pip || { echo "Failed to upgrade pip"; exit 1; }
    pip install gunicorn || { echo "Failed to install Gunicorn"; exit 1; }
    pip install -e . || { echo "Failed to install dependencies"; exit 1; }
}

initialize_db() {  # Create the database. This also populates it with some goals and votes from the default rewards.py
    export FLASK_APP=ownchatbot
    if python -m flask init-db; then
        echo "Database initialized successfully."
    else
        echo "Failed to initialize the database. Please check for errors."
        exit 1  # Exit the script with a non-zero status
    fi
}

generate_key() {
    KEY=$(< /dev/urandom tr -dc 'A-Za-z0-9' | head -c 32)
    echo "$KEY"
}

update_config() {  # Generate key for SECRET_KEY
    local key_name="$1"
    local key_value="$2"
    local bak_file="instance/config.py.bak"

    echo "Go to your Owncast Admin panel -> Integrations -> Access Tokens, and create an access token for OwnchatBot"

    # Update the config file
    if sed -i.bak "s|$key_name = ''|$key_name = '$key_value'|" "instance/config.py"; then
        echo "Set $key_name successfully."
    else
        echo "Failed to set $key_name."
        exit 1  # Exit the script with a non-zero status
    fi

    read -p "Enter the name of the access token: " ACCESS_ID
    if sed -i.bak "s|ACCESS_ID = ''|ACCESS_ID = '$ACCESS_ID'|" "instance/config.py"; then
        echo "Set ACCESS_ID successfully."
    else
        echo "Failed to set ACCESS_ID."
        exit 1  # Exit the script with a non-zero status
    fi

    read -p "Enter the access token: " ACCESS_TOKEN
    if sed -i.bak "s|ACCESS_TOKEN = ''|ACCESS_TOKEN = '$ACCESS_TOKEN'|" "instance/config.py"; then
        echo "Set ACCESS_TOKEN successfully."
    else
        echo "Failed to set ACCESS_TOKEN."
        exit 1  # Exit the script with a non-zero status
    fi

    read -p "Enter the external URL of your Owncast instance, with \"https://\": " OWNCAST_URL
    if sed -i.bak "s|OWNCAST_URL = ''|OWNCAST_URL = '$OWNCAST_URL'|" "instance/config.py"; then
        echo "Set OWNCAST_URL successfully."
        rm "$bak_file"  # Remove the .bak file if the update was successful
    else
        echo "Failed to set OWNCAST_URL."
        exit 1  # Exit the script with a non-zero status
    fi

    read -p "Enter the external URL your OwnchatBot will be using, with \"https://\": " OCB_URL
    if sed -i.bak "s|OCB_URL = ''|OCB_URL = '$OCB_URL'|" "instance/config.py"; then
        echo "Set OCB_URL successfully."
        rm "$bak_file"  # Remove the .bak file if the update was successful
    else
        echo "Failed to set OCB_URL."
        exit 1  # Exit the script with a non-zero status
    fi
}

read -p "This app includes an option to integrate Kofi donations and membership rewards into your stream. If you use this feature, you acknowledge that you alone are responsible for backing up and securing the OwnchatBot folder, so as not to lose any data related to rewards your viewiers earned by spending money on Kofi. The developer(s) of OwnchatBot assume no responsibility for any loss of such data. Do you agree to these terms? Type \"yes\" or \"no\": " agreement  # Prompt the user to accept the agreement

if [[ "$agreement" != "yes" ]]; then
    echo -e "\n\nAgreement declined by user. OwnchatBot not installed.\n\n"
    exit 0
fi

if check_venv; then
    create_venv
else
    exit 1
fi

activate_venv
install_dependencies
initialize_db
deactivate

cp ownchatbot/defaults/*py instance/  # Copy the default config files into the instance folder
mkdir instance/assets  # Create upload folder for alert images

SECRET_KEY=$(generate_key)
update_config "SECRET_KEY" "$SECRET_KEY"

read -p "Please enter the port number you would like OwnchatBot to listen on (default: 8081): " OCB_PORT
OCB_PORT=${OCB_PORT:-8081}

echo "
You're ready to start OwnchatBot! Run:

env/bin/python -m gunicorn --error-logfile ownchatbot.log -b 0.0.0.0:$OCB_PORT -w 1 'ownchatbot:create_app()'

To configure your bot, go to:

$OCB_URL:$OCB_PORT/mgmt

Login to using your owncast admin name and password.
"
