#!/bin/bash
#
# JSRF Unleashed -- the Linux launcher.
#
# Finds your copy of Jet Set Radio Future (the folder with default.xbe in it),
# remembers it, and starts the game with the settings it needs.
#
#   ./jsrf-unleashed                  play (asks where the game is, the first time)
#   ./jsrf-unleashed /path/to/game    use that folder (or a disc image -- see below), and remember it
#   ./jsrf-unleashed --choose         ask where the game is again
#   ./jsrf-unleashed --scale N        internal resolution, 1 to 6 times 640x480 (default 2; 6 is for
#                                     a 4K screen); remembered
#   ./jsrf-unleashed --fullscreen     start full screen
#   ./jsrf-unleashed --portable       keep the settings, cache, logs and unpacked disc images in this
#                                     folder from now on (delete portable.txt to undo)
#   ./jsrf-unleashed --install        add JSRF Unleashed to your applications menu
#   ./jsrf-unleashed --version        which version this is
#
# A disc image (.iso) is unpacked once, by the game itself: nothing else to install.
# In game: F11 (or Alt+Return) full screen, F10 the picture (4:3, 16:9, 21:9), F9 resolution.
#
set -u
HERE="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
CFG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/jsrf-unleashed"
DATA="${XDG_DATA_HOME:-$HOME/.local/share}/jsrf-unleashed"
STATE="${XDG_STATE_HOME:-$HOME/.local/state}/jsrf-unleashed"
# Portable: with a file named portable.txt in this folder (--portable makes
# it), the settings, the cache, the logs and unpacked disc images are kept
# here instead of in ~/.config, ~/.local/share and ~/.local/state, so the
# whole folder can move -- to another machine, onto a USB drive. Saves are in
# the game's folder (UDATA) either way; a game folder inside this one is
# remembered relative to it.
PORTABLE=0
for a in "$@"; do
    if [ "$a" = --portable ] && [ ! -f "$HERE/portable.txt" ]; then
        if printf '%s\n' "While this file is here, JSRF Unleashed keeps its settings, cache, logs and" \
                         "unpacked disc images in this folder. Delete it to keep them in your home" \
                         "folder instead." > "$HERE/portable.txt" 2>/dev/null; then
            # Switching with settings already kept: take them along.
            [ -f "$CFG_DIR/settings" ] && [ ! -f "$HERE/settings" ] && cp "$CFG_DIR/settings" "$HERE/settings"
        else
            printf 'This folder cannot be written to, so it cannot be a portable install: %s\n' "$HERE" >&2
        fi
    fi
done
if [ -f "$HERE/portable.txt" ]; then
    PORTABLE=1; CFG_DIR="$HERE"; DATA="$HERE"; STATE="$HERE"
fi
CFG="$CFG_DIR/settings"
mkdir -p "$CFG_DIR" "$DATA/save" "$STATE/logs"

cfg_get() { [ -f "$CFG" ] && sed -n "s/^$1=//p" "$CFG" | tail -n 1; }
cfg_set() {   # key value: replace or append, keeping every other line
    local tmp="$CFG.tmp"
    { [ -f "$CFG" ] && grep -v "^$1=" "$CFG"; printf '%s=%s\n' "$1" "$2"; } > "$tmp" && mv "$tmp" "$CFG"
}

# A message the player can see: a dialog when there is a desktop to show one.
say() {
    if [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; then
        zenity --info --no-wrap --title="JSRF Unleashed" --text="$1" 2>/dev/null
    elif [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v kdialog >/dev/null 2>&1; then
        kdialog --title "JSRF Unleashed" --msgbox "$1" 2>/dev/null
    else
        printf '%s\n' "$1" >&2
    fi
}
fail() { say "$1"; exit 1; }

is_game() { [ -n "$1" ] && [ -f "$1/default.xbe" ] && [ -d "$1/Media" ]; }

ask_game() {
    local q="Where is Jet Set Radio Future? Pick the folder that contains default.xbe, or the folder your disc image (.iso) is in."
    if [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; then
        zenity --file-selection --directory --title="$q" 2>/dev/null
    elif [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v kdialog >/dev/null 2>&1; then
        kdialog --getexistingdirectory "$HOME" --title "$q" 2>/dev/null
    elif [ -t 0 ]; then
        printf '%s\nFolder: ' "$q" >&2
        local d; IFS= read -r d; printf '%s' "$d"
    fi
}

engine() { LD_LIBRARY_PATH="$HERE/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" "$HERE/bin/jsrf_recomp" "$@"; }

# Files that are not the game JSRF Unleashed runs: say what they are (the
# engine's own check, port/xbe_check.c, names them) and forget them.
refuse() {
    cfg_set game_dir ""
    fail "$(printf "These files won't work with JSRF Unleashed.\n\n%s\n" "$1" | fold -s -w 72)"
}

# The engine's output while it unpacks, line by line as it comes (awk would
# hold it back in a buffer): its progress lines for zenity ("# text" first and
# the percentage last -- zenity closes on 100) or the terminal; everything else,
# its answer, into $STATE/unpack.out.
relay() {
    local mode="$1" name="$2" line d t
    while IFS= read -r line; do
        case "$line" in
            "progress "*)
                set -- $line; d="$2"; t="$3"
                [ "$t" -gt 0 ] 2>/dev/null || continue
                if [ "$mode" = zenity ]; then
                    printf '# Unpacking %s -- %d.%d of %d.%d GB\n%d\n' "$name" \
                        $((d / 1000000000)) $((d / 100000000 % 10)) \
                        $((t / 1000000000)) $((t / 100000000 % 10)) $((d * 100 / t))
                else
                    printf '\r  %d.%d of %d.%d GB' $((d / 1000000000)) $((d / 100000000 % 10)) \
                        $((t / 1000000000)) $((t / 100000000 % 10)) >&2
                fi ;;
            *) printf '%s\n' "$line" >> "$STATE/unpack.out" ;;
        esac
    done
}

# A disc image: unpacked once into ~/.local/share/jsrf-unleashed/<name> (portable:
# into this folder), by the
# engine (--unpack-iso: the unpacker the other apps use, port/ios/xiso.c), so
# nothing else has to be installed. Checked first, so a zip, another game's
# disc or another build of the game is named before anything is unpacked.
# Prints the game folder; nothing if unpacking was cancelled.
from_iso() {
    local iso="$1" name dest why ps
    name="$(basename "$iso")"; name="${name%.*}"; name="${name%.xiso}"
    dest="$DATA/$name"
    if is_game "$dest"; then printf '%s' "$dest"; return; fi
    why="$(engine --check-iso "$iso" 2>/dev/null)"
    case $? in 0) ;; 2|3|4) refuse "$why" ;; *) fail "Could not read $iso." ;; esac
    rm -rf -- "${dest:?}"
    : > "$STATE/unpack.out"
    if [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v zenity >/dev/null 2>&1; then
        engine --unpack-iso "$iso" "$dest" 2>/dev/null | relay zenity "$(basename "$iso")" \
            | zenity --progress --title="JSRF Unleashed" --auto-close \
                     --text="Unpacking $(basename "$iso") -- this happens once." 2>/dev/null
        ps=("${PIPESTATUS[@]}")
        if [ "${ps[2]}" -ne 0 ] && ! grep -qx ok "$STATE/unpack.out"; then   # Cancel
            rm -rf -- "${dest:?}"
            return 0
        fi
    else
        printf 'Unpacking %s -- this happens once. The files go to:\n  %s\n' "$(basename "$iso")" "$dest" >&2
        engine --unpack-iso "$iso" "$dest" 2>/dev/null | relay terminal "$(basename "$iso")"
        ps=("${PIPESTATUS[@]}")
        printf '\n' >&2
    fi
    why="$(grep -vx ok "$STATE/unpack.out")"
    if [ "${ps[0]}" -ne 0 ] || ! is_game "$dest"; then
        rm -rf -- "${dest:?}"
        case "${ps[0]}" in 2|3|4) refuse "$why" ;; esac
        fail "$(printf "The disc image could not be unpacked.\n\n%s\n" "${why:-(exit ${ps[0]})}" | fold -s -w 72)"
    fi
    printf '%s' "$dest"
}

# What was given or picked -> the game folder: the folder itself, the folder
# of a default.xbe, a disc image (any file: the engine says what it is if it
# is not one), or a folder with one disc image in it.
pick() {
    local p="$1" imgs
    if [ -f "$p" ]; then
        case "$(basename "$p")" in
            [Dd][Ee][Ff][Aa][Uu][Ll][Tt].[Xx][Bb][Ee]) p="$(dirname "$p")" ;;
            *) from_iso "$p"; return ;;
        esac
    fi
    if [ -d "$p" ] && ! is_game "$p"; then
        mapfile -t imgs < <(find "$p" -maxdepth 1 -type f \( -iname '*.iso' -o -iname '*.xiso' \) 2>/dev/null | sort)
        if [ "${#imgs[@]}" -eq 1 ]; then from_iso "${imgs[0]}"; return; fi
        [ "${#imgs[@]}" -gt 1 ] && fail "That folder has ${#imgs[@]} disc images in it: give the one of Jet Set Radio Future."
    fi
    printf '%s' "$p"
}

install_desktop() {
    local apps="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
    mkdir -p "$apps"
    cat > "$apps/jsrf-unleashed.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=JSRF Unleashed
Comment=Jet Set Radio Future, running natively
Exec="$HERE/jsrf-unleashed"
Icon=$HERE/share/jsrf-unleashed.png
Terminal=false
Categories=Game;
EOF
    echo "Added JSRF Unleashed to your applications menu ($apps/jsrf-unleashed.desktop)."
}

GAME=""; CHOOSE=0; FULLSCREEN=0
while [ $# -gt 0 ]; do
    case "$1" in
        --choose)     CHOOSE=1 ;;
        --scale)      shift
                      case "${1:-}" in [1-6]) cfg_set scale "$1" ;;
                                       *) fail "--scale takes 1 to 6 (6 is for a 4K screen)." ;; esac ;;
        --fullscreen) FULLSCREEN=1 ;;
        --install)    install_desktop; exit 0 ;;
        --version)    cat "$HERE/VERSION" 2>/dev/null || "$HERE/bin/jsrf_recomp" --version; exit 0 ;;
        --portable)   ;;
        -h|--help)    sed -n '4,21p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
        *)            GAME="$1" ;;
    esac
    shift
done

# The remembered game folder, relative to this folder when portable and inside it.
game_recall() {
    local g; g="$(cfg_get game_dir)"
    case "$g" in "") ;; /*) printf '%s' "$g" ;; *) printf '%s' "$HERE/$g" ;; esac
}
game_store() {
    if [ "$PORTABLE" = 1 ] && [ "${1#"$HERE"/}" != "$1" ]; then cfg_set game_dir "${1#"$HERE"/}"
    else cfg_set game_dir "$1"; fi
}
# Portable, and nothing remembered: the one game folder (or disc image) put in this folder.
game_beside() {
    local d found=""
    for d in "$HERE"/*/; do
        d="${d%/}"
        is_game "$d" || continue
        [ -n "$found" ] && return 0
        found="$d"
    done
    if [ -n "$found" ]; then printf '%s' "$found"; return 0; fi
    local imgs
    mapfile -t imgs < <(find "$HERE" -maxdepth 1 -type f \( -iname '*.iso' -o -iname '*.xiso' \) 2>/dev/null | sort)
    [ "${#imgs[@]}" -eq 1 ] && printf '%s' "${imgs[0]}"
}

# Which game folder: the argument, else the remembered one, else ask.
if [ -z "$GAME" ] && [ "$CHOOSE" = 0 ] && [ "$PORTABLE" = 1 ] && ! is_game "$(game_recall)"; then
    GAME="$(game_beside)"
fi
if [ -n "$GAME" ]; then
    GAME="$(pick "$GAME")" || exit 1
elif [ "$CHOOSE" = 0 ] && is_game "$(game_recall)"; then
    GAME="$(game_recall)"
else
    GAME="$(ask_game)"
    [ -n "$GAME" ] || exit 0
    GAME="$(pick "$GAME")" || exit 1
fi
[ -n "$GAME" ] || exit 0          # unpacking was cancelled
GAME="$(cd "$GAME" 2>/dev/null && pwd)" || fail "That folder does not exist."
is_game "$GAME" || fail "$(printf "That folder has no default.xbe and Media in it, so it isn't the game's files. Pick the folder you extracted the game into, or your disc image (.iso)." | fold -s -w 72)"

# The engine is the standalone US disc's program, translated address for
# address: another build (European, Japanese, a Sega GT 2002 combo disc)
# starts and then crashes a few seconds in. Its own check (port/xbe_check.c)
# says what the files are; exit 3 = another build or another game.
why="$(engine --check-game "$GAME" 2>/dev/null)"
case $? in 2|3) refuse "$why" ;; esac
game_store "$GAME"

SCALE="$(cfg_get scale)"; case "$SCALE" in [1-6]) ;; *) SCALE=2 ;; esac

# The previous run's log is kept (five of them), then a fresh one.
LOG="$STATE/last-run.log"
if [ -f "$LOG" ]; then
    mv "$LOG" "$STATE/logs/run-$(date +%Y%m%d-%H%M%S).log"
    ls -1t "$STATE"/logs/run-*.log 2>/dev/null | tail -n +6 | while IFS= read -r old; do rm -f "$old"; done
fi

export RECOMP_USB=1 RECOMP_GL=1 RECOMP_PB_EXEC=1 RECOMP_VBLANK=1 RECOMP_AC97_READY_NOTRAP=1 \
       RECOMP_TRACE_BUDGET=0 RECOMP_GL_READBACK=0 RECOMP_FPS=60 RECOMP_ABI_RESTORE=1 \
       RECOMP_LOCK_IDLE=1 RECOMP_GL_CURTAIN=skip RECOMP_MUTE=0 RECOMP_WINDOW=1
export RECOMP_GL_SCALE="$SCALE"
[ "$FULLSCREEN" = 1 ] && export RECOMP_FULLSCREEN=1
export JSRF_GAME_DIR="$GAME" JSRF_SAVE_DIR="$DATA/save" JSRF_SETTINGS_FILE="$CFG"
export LD_LIBRARY_PATH="$HERE/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"

cd "$GAME" || exit 1
"$HERE/bin/jsrf_recomp" "$GAME" > "$LOG" 2>&1
status=$?
if [ "$status" -eq 3 ]; then
    # The engine's own check stopped it: not the standalone US disc's files
    # (the log says what they are).
    cfg_set game_dir ""
    say "$(printf "These files won't work with JSRF Unleashed.\n\n%s\n" \
              "$(sed -n 's/^\[XBE\] //p' "$LOG")" | fold -s -w 72)"
elif [ "$status" -ne 0 ]; then
    say "JSRF Unleashed stopped unexpectedly (exit $status).

The log is at:
$LOG

If you report the problem, please attach it."
fi
exit "$status"
