#!/bin/sh
set -eu

[ "${3:-}" = / ] || { echo "Install this package on the current system volume." >&2; exit 1; }
console_uid=$(/usr/bin/stat -f '%u' /dev/console)
console_user=$(/usr/bin/stat -f '%Su' /dev/console)
case "$console_uid" in
    ''|*[!0-9]*) echo "Cannot determine the logged-in desktop user." >&2; exit 1 ;;
esac
[ "$console_uid" -ge 500 ] || { echo "Log in to the Mac desktop before installing this package." >&2; exit 1; }
case "$console_user" in
    root|loginwindow|nobody|'') echo "Log in to a normal Mac account before installing." >&2; exit 1 ;;
esac
[ "$(/usr/bin/id -u "$console_user")" = "$console_uid" ] || {
    echo "The logged-in user changed during installation; retry from the desktop." >&2
    exit 1
}
user_home=$(/usr/bin/dscl . -read "/Users/$console_user" NFSHomeDirectory | /usr/bin/awk 'NR == 1 { sub(/^NFSHomeDirectory: /, ""); print; exit }')
case "$user_home" in
    /*) ;;
    *) echo "Cannot determine the logged-in user's home directory." >&2; exit 1 ;;
esac
xdg_cache=$(/bin/launchctl asuser "$console_uid" /bin/launchctl getenv XDG_CACHE_HOME 2>/dev/null || true)
helper='/Library/Application Support/RelayHubCrossDesk/configure-user.sh'
[ -f "$helper" ] || { echo "Missing CrossDesk configuration helper." >&2; exit 1; }
/bin/launchctl asuser "$console_uid" /usr/bin/sudo -n -H -u "#$console_uid" -- \
    /bin/sh "$helper" "$user_home" "$xdg_cache"
echo "CrossDesk is configured for $console_user. Open CrossDesk from Applications."
exit 0
