#!/bin/bash

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


activate_venv() {
    source env/bin/activate || { echo "Failed to activate virtual environment"; exit 1; }
}

update_modules() {
    pip install --upgrade pip || { echo "Failed to upgrade pip"; exit 1; }  # Upgrade pip
    pip install -e . || { echo "Failed to install/upgrade module"; exit 1; }  # Install/upgrade modules
}

update_config() {
    KOFI_TOKEN=$(grep "^KOFI_TOKEN" instance/config.py | cut -d'=' -f2 | cut -d'#' -f1 | tr -d '[:space:]')  # Get the value of KOFI_TOKEN
    if [ "$KOFI_TOKEN" = "False" ]; then  # So bash doesn't blank the variable in kofi.py if it's False
        KOFI_TOKEN="False" 
    fi
    if [ "$KOFI_INTEGRATION" = "False" ]; then  # Likewise
        KOFI_INTEGRATION="False"
    fi
    if [ -z "$KOFI_INTEGRATION" ]; then  # Due to a bug I missed, the variable may be blank. If so, set to False
        KOFI_INTEGRATION="False"
    fi
    KOFI_INTEGRATION=$(grep "^KOFI_INTEGRATION" instance/config.py | cut -d'=' -f2 | cut -d'#' -f1 | tr -d '[:space:]')  # Get the value of KOFI_INTEGRATION    
    sed -i "s/}/, \'token\': ${KOFI_TOKEN}, \'integration\': ${KOFI_INTEGRATION}}/" instance/kofi.py  # Append those values to kofi.py 
    sed -i "/^KOFI_TOKEN/d" instance/config.py  # Delete KOFI_TOKEN line from config.py
    sed -i "/^KOFI_INTEGRATION/d" instance/config.py  # Delete KOFI_INTEGRATION line from config.py

    sed -i "s/}/,\"gb_name\": \"\"}/" instance/alerts.py  # Append those values to kofi.py
    
    cp ownchatbot/defaults/givebutter.py instance/  # Copy the default givebutter config file into instance/
}

activate_venv
update_modules
deactivate
update_config

echo -e "\nYour OwnchatBot configuration has been upgraded. Look for GiveButter integration settings in the OCB Management Panel.\nHappy streaming!"
