#!/usr/bin/env bash

REGION_PATH="$HOME/.local/share/Steam/steamapps/compatdata/945360/pfx/drive_c/users/steamuser/AppData/LocalLow/Innersloth/Among Us/regionInfo.json"
REGION_URL="https://www.mauq.xyz/files/regionInfo.json"
TEMP_PATH="${REGION_PATH}.mauq-download"
BACKUP_PATH="${REGION_PATH}.mauq-backup"

pause() {
    read -n 1 -s -r -p "Press any key to continue..."
    echo
}

cleanup() {
    rm -f "$TEMP_PATH"
}

trap cleanup EXIT

echo "Downloading custom regions from www.mauq.xyz"
echo "Thanks to Lotus for providing the original installer files."

if ! command -v curl >/dev/null 2>&1; then
    echo "Curl is not installed."
    echo "Download $REGION_URL manually and replace:"
    echo "$REGION_PATH"
    pause
    exit 1
fi

if [ ! -d "$(dirname "$REGION_PATH")" ]; then
    echo "Could not find the Among Us LocalLow folder at:"
    echo "$REGION_PATH"
    echo "Run Among Us at least once and confirm that Steam App ID 945360 uses this compatdata path."
    pause
    exit 1
fi

if ! curl --fail --location --output "$TEMP_PATH" --url "$REGION_URL"; then
    echo "Download failed. Check your internet connection and try again."
    pause
    exit 1
fi

if command -v python3 >/dev/null 2>&1 && ! python3 -m json.tool "$TEMP_PATH" >/dev/null 2>&1; then
    echo "The downloaded region file is not valid JSON. Your existing file was not changed."
    pause
    exit 1
fi

if [ -f "$REGION_PATH" ]; then
    if ! cp "$REGION_PATH" "$BACKUP_PATH"; then
        echo "Could not back up the existing region file. Installation stopped."
        pause
        exit 1
    fi
    echo "Existing region data backed up to:"
    echo "$BACKUP_PATH"
fi

if ! mv -f "$TEMP_PATH" "$REGION_PATH"; then
    echo "Could not replace the region file."
    pause
    exit 1
fi

echo "Installation complete. Open Among Us and select a custom region."
pause
