#!/bin/bash
# shellcheck disable=SC2086
# shellcheck disable=SC2037
# shellcheck disable=SC1001

echo -e "\e[94mSTARTING\e[0m"
FILES=$(find . -name "*.dem")
FILES+=$(find . -name "*.zip")
mapfile -t servers < <(curl -s https://raw.githubusercontent.com/potato-tf/deploy/refs/heads/main/serverlist.json | jq -r '.servers[]')

declare -A server_cpu_check_times

while true; do

    for i in "${servers[@]}"; do server=( $i );
    {
        server_name=${server[1]}
        echo -e "\e[36mREMOVING DUPLICATES ON $server_name\e[0m"
        rsync -avz --chmod=777 -e "ssh -o StrictHostKeyChecking=no -p ${server[0]}" dedup.sh $server_name:~/
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "~/dedup.sh"

    } &
    done
    wait

    echo -e "\e[94mREMOVING DUPLICATES\e[0m"
    ./dedup.sh
    sleep 10s
done &

echo -e "\e[94mFIRST CLEANUP\e[0m"
for i in "${servers[@]}"; do server=( $i );
{

    server_name=${server[1]}
    if [ "$server_name" != "pterodactyl@storage.potato.tf" ]; then
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "~/dedup.sh"
        echo -e "\e[35mSYNCING $server_name TO storage.potato.tf\e[0m"
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "find . -name '*.xz' -type f -print0 | rsync -a -e \"ssh -o StrictHostKeyChecking=no\" --remove-source-files --files-from=- --from0 ./ pterodactyl@storage.potato.tf:/mnt/archival/demoarchive/ && echo -e \"\e[95mSYNCED $server_name to storage.potato.tf\e[0m\""
        echo -e "\e[32mCOMPRESSING DEMOS ON $server_name\e[0m"
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "find . -name '*.dem' -type f -exec xz -9 -T0 {} \; && find . -name '*.dem.xz' -type f -exec sh -c 'mv \"\$1\" \"\${1%.dem.xz}.xz\"' _ {} \; && echo -e \"\e[92mCOMPRESSED demo on $server_name\e[0m\""
        echo -e "\e[32mCOMPRESSING DEMOS ON $server_name\e[0m"
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "find . -name '*.zip' -type f -exec sh -c 'INNER_FILE=\$(unzip -Z1 \"\$1\" | grep \"\\.dem\$\" | head -1); if [ -n \"\$INNER_FILE\" ]; then unzip -p \"\$1\" \"\$INNER_FILE\" | xz -9 -T0 -c > \"\${1%.zip}.dem.xz\"; ~/dedup.sh; fi' _ {} \; && echo -e \"\e[92mCOMPRESSED demo on $server_name\e[0m\""
    fi
}
done

for FILE in $FILES; do

    BASENAME="${FILE:0:-4}"
    OUTFILE="${BASENAME}.xz"
    REMOTE_TARGET=""

    random_server=$(shuf -n 1 -e "${servers[@]}")
    a=( $random_server )

    server_name=${a[1]}
    if [ "$server_name" == "redho@tziah.thebel.net" ] || [ "$server_name" == "pterodactyl@nl3.potato.tf" ]; then
        continue
    fi

    # Check CPU usage on the target server
    if [[ -v ${server_cpu_check_times["$server_name"]} ]]; then
        server_cpu_check_times["$server_name"]=0
    fi

    curtime=$(date +%s)
    sshcmd="ssh -p ${a[0]} -o StrictHostKeyChecking=no"

    if [[ ${server_cpu_check_times["$server_name"]:-0} -lt $curtime ]]; then

        echo -e "\e[93mCHECKING CPU usage on ${server_name}...\e[0m"
        CPU_USAGE=$(${sshcmd} $server_name top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}') || continue

        # skip if CPU usage is greater than 75%
        if (( $(echo "$CPU_USAGE > 75.00" | bc -l) )); then
            echo -e "\e[33mHIGH CPU USAGE on ${server_name} ($CPU_USAGE%), skipping...\e[0m"
            continue
        fi
        server_cpu_check_times["$server_name"]=$((curtime + 3))

    fi

    REMOTE_TARGET="${server_name}:~/${FILE}"
    # rsync_suffix="&& echo -e \"\e[36mRECEIVING '$OUTFILE' from '$server_name'\e[0m\" && rsync -a -e \"ssh -o StrictHostKeyChecking=no\" --remove-source-files ${OUTFILE:2} pterodactyl@storage.potato.tf:/mnt/archival/demoarchive/${OUTFILE:2}"

    if [ "${FILE: -4}" == ".dem" ]; then

        if [[ -n "$REMOTE_TARGET" ]] && [[ $server_name != "pterodactyl@storage.potato.tf" ]]; then
            echo -e "\e[35m($CPU_USAGE%) SENDING $FILE to $server_name...\e[0m" && rsync -a -e "${sshcmd}" --remove-source-files --mkpath $FILE $server_name:~/${FILE:2} && $sshcmd $server_name "xz -9 -T0 ~/${FILE:2} && mv ~/${FILE:2}.xz ~/${OUTFILE:2} && echo -e \"\e[32mRECEIVING '${OUTFILE:2}' from '$server_name'\e[0m\" && rsync -a -e \"ssh -o StrictHostKeyChecking=no\" --remove-source-files ${OUTFILE:2} pterodactyl@storage.potato.tf:/mnt/archival/demoarchive/${OUTFILE:2}" &
        else
            echo -e "\e[92mCOMPRESSING '$FILE'...\e[0m" && xz -9 -T0 "$FILE" && mv "$FILE".xz "$OUTFILE" && echo -e "\e[32mCOMPRESSED '$FILE' to '$OUTFILE'\e[0m" &
        fi

        continue

    elif [ "${FILE: -4}" == ".zip" ]; then

        # Get the inner file name
        INNER_FILE=$(unzip -Z1 "$FILE")

        if [[ -n "$REMOTE_TARGET" ]] && [[ $server_name != "pterodactyl@storage.potato.tf" ]]; then
            echo -e "\e[35m($CPU_USAGE%) SENDING $FILE to $server_name...\e[0m" && rsync -a -e "${sshcmd}" --mkpath $FILE ${server_name}:~/${FILE} && ${sshcmd} ${server_name} "unzip -p ~/${FILE} $INNER_FILE | xz -9 -T0 -c > ~/${OUTFILE:2} && echo -e \"\e[35mRECEIVING ${OUTFILE:2} from $server_name\e[0m\" && rsync -a -e \"ssh -o StrictHostKeyChecking=no\" --remove-source-files ${OUTFILE:2} pterodactyl@storage.potato.tf:/mnt/archival/demoarchive/${OUTFILE:2}" &
        else
            echo -e "\e[36mCOMPRESSING $INNER_FILE from $FILE to $OUTFILE...\e[0m" && unzip -p "$FILE" "$INNER_FILE" | xz -9 -T0 -c > "$OUTFILE" && rm "$FILE" &
        fi
        continue
    fi

done

echo -e "\e[35mFINAL SYNC\e[0m"
for i in "${servers[@]}"; do server=( $i );
    server_name=${server[1]}
    ssh -o StrictHostKeyChecking=no -p ${server[0]} ${server[1]} "find . -name '*.xz' -type f -exec rsync -a -e \"ssh -o StrictHostKeyChecking=no\" --remove-source-files {} pterodactyl@storage.potato.tf:/mnt/archival/demoarchive/ \; && echo -e \"\e[32mSYNCED '$server_name' to 'storage.potato.tf'\e[0m\""
done &
wait

echo -e "\e[35mDONE\e[0m"
