#!/bin/sh
# Create symbolic links from game save folders to documents folder
# Useful if you sync it with syncthing or something similar

set -e

clean() {
    if test $? -ne 0; then
        notify-send "Could not sync ${GAME_NAME}"
    fi
}

trap clean EXIT

command -v xdg-user-dir &>/dev/null &&
    DOCUMETS="$(xdg-user-dir DOCUMENTS)" ||
    DOCUMETS=$HOME/Documents

SAVES_DIR="$DOCUMETS/GameSaves"
test -d "$SAVES_DIR" || exit 1

game_save() {
    GAME_NAME="$1"
    shift
    INSTALL_DIR="$HOME/$1"
    shift

    BACKUP_DIR="$SAVES_DIR/$GAME_NAME"

    mkdir -p "$BACKUP_DIR" "$(dirname "$INSTALL_DIR")"

    if test -d "$INSTALL_DIR" -a ! -L "$INSTALL_DIR"; then
        fd -H -d 1 . "$INSTALL_DIR" |
            xargs -I{} mv "{}" "$BACKUP_DIR"
        sync
        rmdir "$INSTALL_DIR"
    fi

    if test ! -L "$INSTALL_DIR" -o ! -d "$INSTALL_DIR"; then
        ln -sT "$BACKUP_DIR" "$INSTALL_DIR"
    fi
}

game_save mindustry        ".local/share/Mindustry"
game_save minecraft        ".minecraft/saves"
game_save factorio_saves   ".factorio/saves"
game_save factorio_saves   "Games/factorio/saves"
game_save cuphead          "Games/cuphead/drive_c/users/$USER/Application Data/Cuphead"
game_save dusk             "Games/dusk/game/saves"
game_save stardew_valley   ".config/StardewValley"
game_save dishonored       "Games/dishonored/drive_c/users/lelgenio"
game_save hollow_knight    ".config/unity3d/Team Cherry/Hollow Knight"
game_save carrion          ".local/share/Phobia/Carrion"
game_save ULTRAKILL-wine   "Games/ultrakill/drive_c/Program Files/ULTRAKILL/Saves"
game_save marioW           "Games/super-mario-world"
game_save gta_san_andreas  "Games/grand-theft-auto-san-andreas/drive_c/users/$USER/Documents/GTA San Andreas User Files"
game_save hl1              "Games/HalfLife2Source/game/hl1/save"
game_save hl2              "Games/HalfLife2Source/game/hl2/save"
game_save hl2ep1           "Games/HalfLife2Source/game/episodic/save"
game_save hl2ep2           "Games/HalfLife2Source/game/ep2/save"
