#
# Copyright (c) 2025. noBGP, Inc. All rights reserved.
#

_cleanup_legacy_dropin() {
    # Remove the systemd drop-in that old installers used to pass env vars.
    # EnvironmentFile= (no dash prefix) prevents the service from starting
    # if the referenced file is missing.
    if [ -f /etc/systemd/system/nobgp.service.d/env.conf ]; then
        rm -f /etc/systemd/system/nobgp.service.d/env.conf
        rmdir /etc/systemd/system/nobgp.service.d 2>/dev/null || true
        rm -f /etc/nobgp/env
        systemctl daemon-reload
    fi
}

post_install() {
    # Create the symlink
    mkdir -p /usr/local/bin
    ln -sf /usr/share/nobgp/nobgp /usr/local/bin/nobgp

    _cleanup_legacy_dropin

    echo ""
    echo "=== noBGP Agent Installation Complete ==="
    echo ""
    if ! ls /etc/nobgp/*.jwt >/dev/null 2>&1; then
        echo "To get started, register the agent:"
        echo "     sudo nobgp register"
        echo ""
    fi
}

post_upgrade() {
    # Recreate the symlink
    mkdir -p /usr/local/bin
    ln -sf /usr/share/nobgp/nobgp /usr/local/bin/nobgp

    _cleanup_legacy_dropin
}

pre_remove() {
    # Stop and uninstall the nobgp service
    if [ -x "/usr/share/nobgp/nobgp" ]; then
        echo "Uninstalling nobgp service..."
        /usr/share/nobgp/nobgp service uninstall || true
    fi
}

post_remove() {
    # Remove the symlink
    if [ -L "/usr/local/bin/nobgp" ]; then
        echo "Removing nobgp symlink..."
        rm -f /usr/local/bin/nobgp
    fi

    # Remove configuration directory
    if [ -d "/etc/nobgp" ]; then
        echo "Removing nobgp configuration directory..."
        rm -rf /etc/nobgp
    fi
}
