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

echo "STARTING"
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]}
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "~/dedup.sh"

    } &
    done
    wait

    echo "REMOVING DUPLICATES"
    ./dedup.sh
    sleep 5
done &


echo "FIRST CLEANUP"
for i in "${servers[@]}"; do server=( $i );
{

    server_name=${server[1]}
    if [ "$server_name" != "pterodactyl@storage.potato.tf" ]; then
        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"
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "find . -name '*.xz' -type f -print0 | rsync -av --remove-source-files --files-from=- --from0 ./ storage.potato.tf:/mnt/archival/demoarchive/ && echo -e \"\e[35mSYNCED '$server_name' to 'storage.potato.tf'\e[0m\""
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "find . -name '*.dem' -type f -exec xz -9 -T0 {} \; && mv ./*.dem.xz ./*.xz 2>/dev/null && echo -e \"\e[35mCOMPRESSED demo on $server_name\e[0m\"" &
        ssh -o StrictHostKeyChecking=no -p ${server[0]} $server_name "find . -name '*.zip' -type f -exec sh -c 'unzip -p \"\$1\" *.dem | xz -9 -T0 -c > \"\${1%.zip}.dem.xz\"; ~/dedup.sh' _ {} \; && echo -e \"\e[35mCOMPRESSED demo on $server_name\e[0m\""
    fi
} &
done
wait

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[94mCHECKING 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 50%
        if (( $(echo "$CPU_USAGE > 50.00" | bc -l) )); then
            echo "HIGH CPU USAGE on ${server_name} ($CPU_USAGE%), skipping..."
            continue
        fi
        server_cpu_check_times["$server_name"]=$((curtime + 3))

    fi

    REMOTE_TARGET="${server_name}:~/${FILE}"
    rsync_suffix="&& echo -e \"\e[32mRECEIVING '$OUTFILE' from '$server_name'\e[0m\" && rsync -a --remove-source-files -e \"ssh -o StrictHostKeyChecking=no\" ${OUTFILE:2} 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[92m($CPU_USAGE%) SENDING '$FILE' to '${server_name}'...\e[0m"
            rsync -a --remove-source-files --mkpath -e "${sshcmd}" $FILE $server_name:~/${FILE:2} && $sshcmd $server_name "xz -9 -T0 ~/$FILE && mv ~/$FILE.xz ~/${OUTFILE:2} $rsync_suffix" &
        else
            echo -e "\e[95mCOMPRESSING '$FILE'...\e[0m"
            xz -9 -T0 "$FILE" && mv "$FILE".xz "$OUTFILE" && echo -e "\e[35mCOMPRESSED '$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[92m($CPU_USAGE%) SENDING '$FILE' to '${server_name}'...\e[0m"
            rsync -a --mkpath -e "${sshcmd}" $FILE ${server_name}:~/${FILE} && ${sshcmd} ${server_name} "unzip -p ~/$FILE $INNER_FILE | xz -9 -T0 -c > ${OUTFILE}" $rsync_suffix &
        else
            echo -e "\e[95mCOMPRESSING '$INNER_FILE' from '$FILE' to '$OUTFILE'...\e[0m"
            # Stream unzip directly to xz
            unzip -p "$FILE" "$INNER_FILE" | xz -9 -T0 -c > "$OUTFILE"

            # Move into place and remove original zip
            rm "$FILE"
        fi

        continue
    fi

done

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

echo "DONE"