#!/bin/sh
set -u

umask 077

data_home=${XDG_DATA_HOME:-"$HOME/.local/share"}
app_root=${ICQ2_APP_ROOT:-"$data_home/icq2/gui-client"}
updater="$app_root/runtime/icq2-update"

if [ -x "$updater" ]; then
    "$updater" --activate-staged >/dev/null 2>&1 || true
fi

current="$app_root/current"
client="$current/bin/icq-desktop"
if [ ! -x "$client" ]; then
    printf '%s\n' "ICQ2 Desktop is not installed correctly. Run the installer again." >&2
    exit 69
fi

if [ "${ICQ2_DISABLE_BACKGROUND_UPDATE:-0}" != 1 ] && [ -x "$updater" ]; then
    "$updater" --background >/dev/null 2>&1 &
fi

health_file="$app_root/startup-health.$$"
rm -f -- "$health_file"
ICQ2_UPDATE_HEALTH_FILE="$health_file" "$client" "$@"
status=$?

if [ -x "$updater" ]; then
    version=$($client --version 2>/dev/null || true)
    healthy=$(sed -n '1p' "$health_file" 2>/dev/null || true)
    rm -f -- "$health_file"
    if [ "$healthy" = "$version" ]; then
        "$updater" --mark-healthy "$version" >/dev/null 2>&1 || true
    elif [ "$status" -ne 0 ]; then
        "$updater" --mark-start-failed "$version" >/dev/null 2>&1 || true
    fi
    "$updater" --activate-staged >/dev/null 2>&1 || true
fi

exit "$status"
