post_install() {
    # Create stegasoo system user if it doesn't exist
    if ! getent passwd stegasoo >/dev/null; then
        useradd -r -s /usr/bin/nologin -d /opt/stegasoo stegasoo
        echo "Created system user 'stegasoo'"
    fi

    # Set ownership of instance directory for Flask
    chown -R stegasoo:stegasoo /opt/stegasoo/venv/var/app-instance 2>/dev/null || true

    echo ""
    echo "==============================================="
    echo "  Stegasoo installed successfully!"
    echo "==============================================="
    echo ""
    echo "CLI usage:"
    echo "  stegasoo --help"
    echo "  stegasoo generate        # Generate credentials"
    echo "  stegasoo encode          # Encode a message"
    echo "  stegasoo decode          # Decode a message"
    echo ""
    echo "-----------------------------------------------"
    echo "  Web UI Service"
    echo "-----------------------------------------------"
    echo "  Port: 5000 (HTTP)"
    echo "  Start:   sudo systemctl start stegasoo-web"
    echo "  Enable:  sudo systemctl enable stegasoo-web"
    echo "  Status:  sudo systemctl status stegasoo-web"
    echo "  Access:  http://localhost:5000"
    echo ""
    echo "-----------------------------------------------"
    echo "  REST API Service"
    echo "-----------------------------------------------"
    echo "  Port: 8000 (HTTPS by default)"
    echo "  Start:   sudo systemctl start stegasoo-api"
    echo "  Enable:  sudo systemctl enable stegasoo-api"
    echo "  Status:  sudo systemctl status stegasoo-api"
    echo "  Access:  https://localhost:8000"
    echo ""
    echo "-----------------------------------------------"
    echo "  HTTPS Configuration"
    echo "-----------------------------------------------"
    echo "  The API generates self-signed certs on first run."
    echo "  To pre-generate or use custom certificates:"
    echo ""
    echo "  # Generate self-signed certs"
    echo "  sudo -u stegasoo stegasoo api tls generate"
    echo ""
    echo "  # Use custom certs (edit the service file)"
    echo "  sudo systemctl edit stegasoo-api"
    echo "  # Add: ExecStart= with --cert and --key flags"
    echo ""
    echo "  # Create API keys for authentication"
    echo "  sudo -u stegasoo stegasoo api keys create <name>"
    echo ""
    echo "==============================================="
    echo ""
}

post_upgrade() {
    post_install
}

pre_remove() {
    # Stop services if running
    systemctl stop stegasoo-web 2>/dev/null || true
    systemctl stop stegasoo-api 2>/dev/null || true
}

post_remove() {
    # Optionally remove the stegasoo user
    # userdel stegasoo 2>/dev/null || true
    echo "Stegasoo removed. User 'stegasoo' was not removed."
    echo "To remove: userdel stegasoo"
}
