#!/bin/bash
# setup-odoopos-autostart.sh — make OdooPOS autorun on boot (Raspberry Pi OS Bookworm, labwc/Wayland)
#
# OdooPOS is a GUI Qt app: it must be launched INSIDE the desktop session
# (XDG autostart), NOT as a systemd system service — a system unit has no
# Wayland/X display and will never show a window.
#
# What this script does (idempotent, safe to re-run):
#   1. Removes any previously-created odoopos systemd unit (wrong method)
#   2. Installs ~/.config/autostart/odoopos.desktop that launches OdooPOS
#      via lwrespawn, so it also auto-relaunches after a crash or
#      `pkill OdooPOS` (the standard deploy flow)
#   3. Optionally starts OdooPOS immediately in the running session
#
# Run as the kiosk desktop user (e.g. pamella-raspi), NOT with sudo:
#   bash setup-odoopos-autostart.sh
set -euo pipefail

# NOTE: pakai path langsung, BUKAN symlink /usr/local/bin/odoopos — run-odoopos.sh
# di .deb <= 1.0.611 memakai dirname "$0" tanpa readlink -f, jadi rusak via symlink.
LAUNCHER=/opt/odoopos/run-odoopos.sh
AUTOSTART_DIR="$HOME/.config/autostart"
DESKTOP_FILE="$AUTOSTART_DIR/odoopos.desktop"

log() { echo -e "\033[0;32m[autostart]\033[0m $*"; }
warn() { echo -e "\033[1;33m[autostart]\033[0m $*"; }
die() { echo -e "\033[0;31m[autostart]\033[0m $*" >&2; exit 1; }

[ "$(id -u)" -eq 0 ] && die "Jalankan sebagai user desktop (tanpa sudo), bukan root."
[ -x "$LAUNCHER" ] || die "$LAUNCHER tidak ditemukan — install package odoopos dulu (apt install odoopos)."

# Bersihkan sisa loop lwrespawn lama yang mungkin masih retry dengan path salah
pkill -f "lwrespawn /usr/local/bin/odoopos" 2>/dev/null || true

# 1. Clean up wrong systemd-based attempts (system and user scope)
if [ -f /etc/systemd/system/odoopos.service ] || systemctl list-unit-files 2>/dev/null | grep -q '^odoopos\.service'; then
    warn "Menemukan systemd unit odoopos — metode ini salah untuk app GUI, dihapus."
    sudo systemctl disable --now odoopos.service 2>/dev/null || true
    sudo rm -f /etc/systemd/system/odoopos.service
    sudo systemctl daemon-reload
fi
if [ -f "$HOME/.config/systemd/user/odoopos.service" ]; then
    warn "Menghapus user-level systemd unit odoopos."
    systemctl --user disable --now odoopos.service 2>/dev/null || true
    rm -f "$HOME/.config/systemd/user/odoopos.service"
    systemctl --user daemon-reload 2>/dev/null || true
fi

# 2. Pick the exec line: lwrespawn (stock on RPi OS Bookworm) gives crash/pkill
#    respawn; fall back to plain launcher when absent (e.g. older X11 images).
if [ -x /usr/bin/lwrespawn ]; then
    RUN_CMD="/usr/bin/lwrespawn $LAUNCHER"
else
    warn "lwrespawn tidak ada — OdooPOS tetap autorun saat boot tapi tidak auto-relaunch setelah pkill."
    RUN_CMD="$LAUNCHER"
fi

# Wrapper: OdooPOS bundle tidak punya Qt wayland plugin — wajib XWayland (xcb),
# jadi fallback DISPLAY=:0 kalau labwc belum meng-export DISPLAY saat autostart.
WRAPPER="$HOME/.local/bin/odoopos-autostart"
mkdir -p "$HOME/.local/bin"
cat > "$WRAPPER" <<EOF
#!/bin/bash
export DISPLAY="\${DISPLAY:-:0}"
exec $RUN_CMD
EOF
chmod +x "$WRAPPER"

mkdir -p "$AUTOSTART_DIR"
cat > "$DESKTOP_FILE" <<EOF
[Desktop Entry]
Type=Application
Name=OdooPOS
Comment=Point of Sales — autostart kiosk
Exec=$WRAPPER
Terminal=false
X-GNOME-Autostart-enabled=true
EOF
log "Terpasang: $DESKTOP_FILE"
log "Wrapper : $WRAPPER -> $RUN_CMD"

# 3. Start it now if a desktop session is already running and OdooPOS isn't
if pgrep -x OdooPOS >/dev/null; then
    log "OdooPOS sudah jalan — tidak perlu start ulang."
elif [ -S "/run/user/$(id -u)/wayland-0" ] || [ -n "${DISPLAY:-}" ]; then
    log "Session aktif terdeteksi — menjalankan OdooPOS sekarang."
    XDG_RUNTIME_DIR="/run/user/$(id -u)" setsid -f "$WRAPPER" >/dev/null 2>&1 || true
    sleep 5
    pgrep -x OdooPOS >/dev/null && log "OdooPOS running (PID $(pgrep -x OdooPOS | head -1))." \
        || warn "OdooPOS belum terdeteksi — cek manual atau reboot."
else
    log "Tidak ada session desktop aktif — OdooPOS akan jalan otomatis saat boot berikutnya."
fi

log "Selesai. Verifikasi penuh: reboot lalu cek 'pgrep -a OdooPOS'."
