#!/bin/sh
# /usr/bin/mycellium-bootstrap-private — installed by mycellium-ui-private.deb
#
# Wrapper around the mycelium-private daemon that guarantees a clean
# start every time. Without this, an orphan daemon left over from a
# previous run (which the user-space launcher cannot SIGKILL because
# it runs as root via pkexec) would block the next start with one of:
#
#   * EBUSY on TUN device creation
#   * "Address in use" on the JSON-RPC port (hardcoded 8990 in 0.6.1)
#   * "Failed to bind multicast discovery socket" on UDP 9650
#
# This script runs under the same elevated context as the daemon
# itself (single pkexec call), so polkit's auth_admin_keep caching
# only fires one prompt per session.

set -e

# Best-effort cleanup. Errors ignored so the exec at the end always
# runs even on a clean machine. We pkill both `mycelium` and
# `mycelium-private` because the public-variant orphan would clash
# on UDP/9650 and TCP/8990 just as readily.
pkill -9 -x mycelium-private 2>/dev/null || true
pkill -9 -x mycelium 2>/dev/null || true
sleep 0.3
ip link del mycelium 2>/dev/null || true
ip link del mycel0 2>/dev/null || true

exec /usr/bin/mycelium-private "$@"
