#!/bin/sh
set -eu

umask 077
export LC_ALL=C

version=0.2.02a
command_name=$(basename -- "$0")
self=$(readlink -f -- "$0") || {
    printf '%s\n' "ICQ2 could not locate its installed bootstrap files." >&2
    exit 1
}
bootstrap_root=$(dirname -- "$self")
payload="$bootstrap_root/$version"

case "$command_name" in
    icq2-tui|icq2-update) ;;
    *) printf '%s\n' "Run icq2-tui or icq2-update." >&2; exit 2 ;;
esac

[ "$(id -u)" -ne 0 ] || {
    printf '%s\n' "Run ICQ2 as your normal desktop user, not as root." >&2
    exit 1
}
[ -n "${HOME:-}" ] || {
    printf '%s\n' "ICQ2 could not determine the current user's home directory." >&2
    exit 1
}

data_home=${XDG_DATA_HOME:-"$HOME/.local/share"}
app_root=${ICQ2_APP_ROOT:-"$data_home/icq2/client"}
launcher="$app_root/runtime/icq2-launcher"
updater="$app_root/runtime/icq2-update"
client="$app_root/current/bin/icq-tui"

if [ ! -x "$launcher" ] || [ ! -x "$updater" ] || [ ! -x "$client" ]; then
    installer="$payload/install.sh"
    archive="$payload/icq2-$version-linux-x86_64.tar.gz"
    signature="$archive.sig"
    public_key="$payload/icq2-unix-update-public-key.pem"
    [ -x "$installer" ] && [ -f "$archive" ] &&
        [ -f "$signature" ] && [ -f "$public_key" ] || {
            printf '%s\n' "The installed ICQ2 bootstrap package is incomplete." >&2
            exit 1
        }
    printf '%s\n' "Preparing ICQ2 $version for this user..."
    "$installer" --archive "$archive" --signature "$signature" \
        --public-key "$public_key"
fi

case "$command_name" in
    icq2-tui) exec "$launcher" "$@" ;;
    icq2-update) exec "$updater" "$@" ;;
esac
