#!/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


