#!/bin/bash
set -e

PILOT_VENV="/opt/pilot/venv"
PILOT_DAEMON="/opt/pilot/daemon"

case "$1" in
    configure)
        # Create Python virtual environment and install daemon
        if [ ! -d "$PILOT_VENV" ]; then
            python3 -m venv "$PILOT_VENV"
        fi

        "$PILOT_VENV/bin/pip" install --quiet --upgrade pip
        "$PILOT_VENV/bin/pip" install --quiet "$PILOT_DAEMON"

        # Create symlink for the daemon binary
        ln -sf "$PILOT_VENV/bin/pilot-daemon" /usr/local/bin/pilot-daemon

        # Install the systemd user service for all users
        mkdir -p /usr/lib/systemd/user
        cp /opt/pilot/pilot-daemon.service /usr/lib/systemd/user/pilot-daemon.service
        systemctl --global daemon-reload 2>/dev/null || true

        # Install PolicyKit policy
        mkdir -p /usr/share/polkit-1/actions
        cp /opt/pilot/com.pilot.policy /usr/share/polkit-1/actions/com.pilot.policy

        # Install desktop file
        cp /opt/pilot/pilot.desktop /usr/share/applications/pilot.desktop
        update-desktop-database /usr/share/applications 2>/dev/null || true

        echo "Pilot installed successfully."
        echo "Start the daemon: systemctl --user start pilot-daemon"
        echo "Or launch Pilot from the application menu."
        ;;
esac

exit 0
