#!/bin/bash
set +e

DIR="$(cd "$(dirname "$0")" && pwd)"
consoleUser="$(stat -f%Su /dev/console)"

if [ -z "$consoleUser" ] || [ "$consoleUser" = "root" ]; then
    consoleUser="$(id -un)"
fi
if [ "$consoleUser" = "root" ]; then
    echo "postinstall: cannot determine console user — skipping registration" >&2
    exit 0
fi
uid="$(id -u "$consoleUser")"

run_as_user() {
    if [ "$(id -u)" = "0" ]; then
        launchctl asuser "$uid" sudo -u "$consoleUser" "$@"
    else
        "$@"
    fi
}

homeDir="$(dscl . -read "/Users/$consoleUser" NFSHomeDirectory 2>/dev/null | awk '{print $2}')"
[ -z "$homeDir" ] && homeDir="/Users/$consoleUser"
target="$homeDir/Library/Input Methods"

if [ "$(id -u)" = "0" ]; then
    check="$target"
    while [ ! -e "$check" ] && [ "$check" != "/" ]; do
        check="$(dirname "$check")"
    done
    real="$(cd "$check" 2>/dev/null && pwd -P)"
    if [ "$real" != "$check" ]; then
        echo "postinstall: refusing — symlink escape" >&2
        exit 1
    fi
fi

if [ -d "/Library/Input Methods/VieLotusIM.app" ]; then
    APP="/Library/Input Methods/VieLotusIM.app"
elif [ -d "$target/VieLotusIM.app" ]; then
    APP="$target/VieLotusIM.app"
else
    APP="/Library/Input Methods/VieLotusIM.app"
fi

# Kill old running instance
run_as_user pkill -9 VieLotusIM 2>/dev/null

# Register with LaunchServices
LSREGISTER="/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister"
"$LSREGISTER" -f "$APP" 2>/dev/null

# Register TIS input source and sync HIToolbox enabled/selected sources
if ! run_as_user "$DIR/register-source" "$APP"; then
    echo "postinstall: register-source failed" >&2
fi

# Refresh macOS TextInputMenuAgent and pre-warm VieLotusIM server so typing works immediately
run_as_user killall TextInputMenuAgent 2>/dev/null || true
if [ -x "$APP/Contents/MacOS/VieLotusIM" ]; then
    run_as_user "$APP/Contents/MacOS/VieLotusIM" >/dev/null 2>&1 &
fi

# Clean up temporary previous backups
rm -rf "$APP.previous" 2>/dev/null || true
if [ -n "$target" ] && [ -d "$target/VieLotusIM.app.previous" ]; then
    rm -rf "$target/VieLotusIM.app.previous" 2>/dev/null || true
fi

# Send user notification confirming zero-step activation
run_as_user osascript -e 'display notification "Bộ gõ Sen Việt đã được tự động thêm và kích hoạt trên thanh Menu — bạn có thể gõ tiếng Việt ngay!" with title "Sen Việt đã sẵn sàng" subtitle "Cài đặt & kích hoạt tự động thành công"' 2>/dev/null || true

exit 0
