#!/bin/sh
# Migrate the old per-user Linux installation to the system DEB/RPM package.
# User data stays in place; only launchers and the shadowing systemd unit move
# to the canonical package under /usr and /opt.
set -eu

home_dir="${1:-${HOME:-}}"
[ -n "$home_dir" ] || exit 0

legacy_root="$home_dir/.local/share/sufficit-ai-genius"
legacy_launcher="$legacy_root/genius"
legacy_desktop_exe="$legacy_root/desktop/Sufficit.AI.Genius.Desktop"
legacy_menu="$home_dir/.local/share/applications/sufficit-ai-genius.desktop"
legacy_unit="$home_dir/.config/systemd/user/sufficit-ai-genius.service"
system_launcher="${GENIUS_SYSTEM_LAUNCHER:-/usr/bin/sufficit-ai-genius}"
system_desktop="${GENIUS_SYSTEM_DESKTOP:-/opt/sufficit-ai-genius/desktop/Sufficit.AI.Genius.Desktop}"

# Do not touch a custom installation that merely happens to use the same app
# id. The old installer always writes this exact launcher contract.
if [ ! -f "$legacy_launcher" ] \
    || ! grep -Fq 'desktop/Sufficit.AI.Genius.Desktop' "$legacy_launcher"; then
    exit 0
fi

[ -x "$system_launcher" ] || exit 0
[ -x "$system_desktop" ] || exit 0

write_forwarder() {
    target="$1"
    target_dir=$(dirname "$target")
    mkdir -p "$target_dir"
    temporary=$(mktemp "$target_dir/.genius-migration.XXXXXX")
    cat > "$temporary" <<EOF
#!/bin/sh
# Compatibility forwarder created by the Sufficit AI Genius system package.
exec "$system_launcher" "\$@"
EOF
    chmod 755 "$temporary"
    mv -f "$temporary" "$target"
}

# A per-user desktop entry wins over /usr/share/applications and kept opening
# the old binaries even after dpkg/rpm had successfully installed the update.
if [ -f "$legacy_menu" ] \
    && grep -Fq "Exec=$legacy_launcher" "$legacy_menu"; then
    rm -f "$legacy_menu"
fi

# Likewise, the per-user unit shadows the vendor unit from /usr/lib/systemd.
# Removing only this known unit makes the existing enablement link resolve to
# the packaged service; configuration and state remain untouched.
if [ -f "$legacy_unit" ] \
    && grep -Fq 'ExecStart=%h/.local/share/sufficit-ai-genius/service/' "$legacy_unit"; then
    rm -f "$legacy_unit"
fi

# The affected updater restarts Environment.ProcessPath. Forward both legacy
# entry points so that even that already-running old process opens the package
# that has just been installed instead of reopening itself.
write_forwarder "$legacy_launcher"
if [ -e "$legacy_desktop_exe" ]; then
    write_forwarder "$legacy_desktop_exe"
fi

