#!/bin/bash
# https://www.baeldung.com/linux/monitor-changes-directory-tree
export LOG_TAG="Qbt Port Forward"
export LOG_PRIO=5
ROOT_SRC_DIR="/opt/shared/pia/"

update_qbt_config() {
    local DC_FILE=/opt/appdata/.docker-compose/docker-compose.yml
    docker kill qbt
    NEW_PORT=$(</opt/shared/pia/port.dat)
    echo "$NEW_PORT"
    sed -i "s/Session\\\Port=.*/Session\\\Port=$NEW_PORT/g" /opt/appdata/qbt/config/qBittorrent.conf
    cd /opt/appdata/ ; sudo docker-compose -f $DC_FILE up -d --force-recreate --no-deps qbt
}

file_removed() {
    TIMESTAMP=`date`
    # echo "[$TIMESTAMP]: The file $1$2 was removed" >> monitor_log
    logger -p $LOG_PRIO -t "$LOG_TAG" "[$TIMESTAMP]: The file $1$2 was removed"
}

file_modified() {
    TIMESTAMP=`date`
    # echo "[$TIMESTAMP]: The file $1$2 was modified" >> monitor_log
    logger -p $LOG_PRIO -t "$LOG_TAG" "[$TIMESTAMP]: The file $1$2 was modified"
}

file_created() {
    TIMESTAMP=`date`
    # echo "[$TIMESTAMP]: The file $1$2 was created" >> monitor_log
    logger -p $LOG_PRIO -t "$LOG_TAG" "[$TIMESTAMP]: The file $1$2 was created"
}

inotifywait -q -m -r -e modify $ROOT_SRC_DIR | while read DIRECTORY EVENT FILE; do
    file_modified "$DIRECTORY" "$FILE"
    sleep 20
    update_qbt_config
done

source /opt/scripts_local/shared_functions.sh

MY_CRED="username=admin&password=Vocalize_Void_Rage_Visor_Ladies_Undercook_Spokesman_Fraternal"
MY_HEADER="Referer: https://qbt.noxs.me"
MY_COOKIE=$(curl -i --header "$MY_HEADER" --data "$MY_CRED" https://qbt.noxs.me/api/v2/auth/login | grep SID= | cut -d ';' -f 1 | cut -d ' ' -f 2)
if ! _isVarEmpty "$MY_COOKIE"; then
  if ( curl https://qbt.noxs.me/api/v2/app/set_preferences json={"listen_port": 66666} --cookie "$MY_COOKIE" ) ; then
    exit 0
  else
    exit 1
  fi
fi
