#!/bin/bash

###DEBHELPER###

set -e

chmod +x /usr/bin/ws-indicate
chmod +x /usr/bin/ws-heartbeat
chmod +x /usr/bin/ws-run-audio
chmod +x /usr/bin/ws-run-sensors
chmod +x /usr/bin/ws-network

chown root:root /etc/sudoers.d/ws

case "$1" in
    configure)
        echo "Configuring WildlifeSystems services..."
        
        # Clean up old service file locations from previous versions
        for old_file in /etc/systemd/system/ws-*.service /etc/systemd/system/ws-*.timer; do
            if [ -f "$old_file" ]; then
                echo "Removing old service file: $old_file"
                rm -f "$old_file" || true
            fi
        done
        
        # Reload systemd to pick up new service files
        systemctl daemon-reload
        
        # Check if we have saved service states
        if [[ -f /var/lib/ws-node/enabled-services.txt ]]; then
            echo "Restoring previously enabled services..."
            while IFS= read -r unit; do
                if [[ -n "$unit" ]]; then
                    echo "Enabling $unit"
                    deb-systemd-helper enable "$unit" || true
                fi
            done < /var/lib/ws-node/enabled-services.txt
        fi
        
        if [[ -f /var/lib/ws-node/active-services.txt ]]; then
            echo "Restoring previously active services..."
            while IFS= read -r unit; do
                if [[ -n "$unit" ]]; then
                    echo "Starting $unit"
                    deb-systemd-invoke start "$unit" || true
                fi
            done < /var/lib/ws-node/active-services.txt
        fi
        
        # Clean up state files after restore
        rm -f /var/lib/ws-node/enabled-services.txt || true
        rm -f /var/lib/ws-node/active-services.txt || true
        
        echo "WildlifeSystems services configured successfully"
        ;;
        
    abort-upgrade|abort-remove|abort-deconfigure)
        # Handle rollback scenarios
        echo "Handling package configuration abort for case: $1"
        ;;
        
    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
        ;;
esac

exit 0
