#!/bin/sh
set -e

# Source debconf library
. /usr/share/debconf/confmodule

# Define package name
PACKAGE="apt-ostreed"

# Function to log messages
log() {
    echo "$PACKAGE: $1" >&2
}

# Function to check if systemd is available
check_systemd() {
    if ! command -v systemctl >/dev/null 2>&1; then
        return 1
    fi
    return 0
}

# Function to stop and disable the service
cleanup_service() {
    if ! check_systemd; then
        return 0
    fi

    log "Cleaning up apt-ostreed service..."

    # Stop the service if running
    if systemctl is-active --quiet apt-ostreed.service; then
        if systemctl stop apt-ostreed.service; then
            log "apt-ostreed service stopped"
        else
            log "Warning: Failed to stop apt-ostreed service"
        fi
    fi

    # Disable the service
    if systemctl is-enabled --quiet apt-ostreed.service; then
        if systemctl disable apt-ostreed.service; then
            log "apt-ostreed service disabled"
        else
            log "Warning: Failed to disable apt-ostreed service"
        fi
    fi

    # Reload systemd daemon
    systemctl daemon-reload
}

# Function to cleanup directories (only on purge)
cleanup_directories() {
    if [ "$1" = "purge" ]; then
        log "Purging apt-ostreed directories..."
        
        # Remove log files (but keep directory structure)
        rm -f /var/log/apt-ostreed/*
        
        # Remove cache files (but keep directory structure)
        rm -rf /var/cache/apt-ostree/*
        
        # Remove state files (but keep directory structure)
        rm -rf /var/lib/apt-ostree/*
        
        log "Directory cleanup completed"
    fi
}

# Main execution
case "$1" in
    remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
        cleanup_service
        ;;
    purge)
        cleanup_service
        cleanup_directories "$1"
        ;;
    *)
        log "Unknown action: $1"
        exit 1
        ;;
esac

exit 0
