#!/bin/sh
# {{ app_display }} uninstaller — macOS and Linux.
#
# Generated by ariza from {{ app_name }}'s ariza.toml. Do not edit this
# file: edit ariza's resources/templates/uninstall-posix.sh.j2 and re-run
# `ariza installers --app=<this repository>`.
#
#   curl -fsSL {{ raw_base }}/uninstall.sh | sh
#   sh uninstall.sh
#
# Removes exactly what install.sh created: the versions directory, the
# `current` symlink, the ~/.local/bin link, and the marked PATH block in
# your shell rc files. Anything {{ app_display }} itself wrote — your data,
# your configuration — is left alone, and this says where it is rather
# than deciding for you.

set -eu

APP_DISPLAY='{{ app_display }}'
APP_EXEC='{{ app_exec }}'

ARIZA_PATH_MARKER="# >>> $APP_EXEC PATH >>>"
ARIZA_PATH_END="# <<< $APP_EXEC PATH <<<"

ARIZA_ROOT="${XDG_DATA_HOME:-$HOME/.local/share}/$APP_EXEC"
ARIZA_BIN_DIR="$HOME/.local/bin"
ARIZA_STATE="${XDG_STATE_HOME:-$HOME/.local/state}/$APP_EXEC"

############################# common runtime ##################################
{{ lib_posix | safe }}
###############################################################################

ariza_usage() {
    cat <<USAGE
Usage: uninstall.sh [-h|--help]

Removes $ARIZA_ROOT, the $ARIZA_BIN_DIR/$APP_EXEC link, and the
$APP_EXEC PATH block from your shell rc files. Nothing else is touched.
USAGE
}

ariza_remove_bin_link() {
    _bin="$ARIZA_BIN_DIR/$APP_EXEC"
    if [ -L "$_bin" ]; then
        # Only ours. Someone may have their own $APP_EXEC on PATH, and a
        # tool that deletes a link it did not create is a tool nobody
        # runs twice.
        _target=$(readlink "$_bin" || true)
        case $_target in
            "$ARIZA_ROOT"/*)
                rm -f "$_bin"
                ariza_ok "removed $_bin"
                ;;
            *)
                ariza_warn "$_bin points at $_target, which is not ours -- leaving it alone"
                ;;
        esac
    elif [ -e "$_bin" ]; then
        ariza_warn "$_bin is not a symlink -- leaving it alone"
    fi
}

main() {
    case ${1:-} in
        -h|--help) ariza_usage; exit 0 ;;
        '') ;;
        *) ariza_err "unknown option '$1' -- run with --help" ;;
    esac

    ariza_log "uninstalling $APP_DISPLAY"

    if [ -d "$ARIZA_ROOT" ]; then
        rm -rf "$ARIZA_ROOT"
        ariza_ok "removed $ARIZA_ROOT"
    else
        ariza_log "nothing installed at $ARIZA_ROOT"
    fi

    ariza_remove_bin_link
    ariza_unpersist_path

    printf '\n'
    ariza_ok "$APP_DISPLAY uninstalled"
    printf '    Not touched, because this installer never wrote them:\n'
    printf '      %s\n' "$ARIZA_STATE"
    printf '      any data or configuration %s created for you\n' "$APP_DISPLAY"
}

main "$@"
