#!/usr/bin/bash
# /usr/bin/electrum-btcq launcher.
#
# We use python3 -I -c to avoid two problems that arise when exec-ing
# the entry script directly:
#
# 1. python3 script.py inserts dirname(script) at sys.path[0], which
#    puts /usr/lib/electrum-btcq/electrum/ first.  That shadows stdlib
#    modules (e.g. asyncio's deep import of logging) with the electrum
#    package's own logging.py, causing an ImportError at startup.
#
# 2. User-site packages (~/.local/lib/...) can override the bundled venv.
#
# By using -I -c we control sys.path entirely:
#   [0] "/usr/lib/electrum-btcq/venv"  — bundled deps
#   [1] "/usr/lib/electrum-btcq"       — electrum package (import electrum.*)
#
# The entry script (electrum/electrum-btcq) is loaded by importlib so
# it runs as __main__ with the correct sys.argv (first element rewritten
# to the script path for conventional argv[0] semantics).

SCRIPT="/usr/lib/electrum-btcq/electrum/electrum-btcq"
exec /usr/bin/python3 -I -c "
import sys, importlib.util, importlib.machinery
# Prepend bundled venv and wallet source; stdlib paths are already in
# sys.path from the interpreter itself (only user-site and PYTHONPATH
# are suppressed by -I).
sys.path = [
    '/usr/lib/electrum-btcq/venv',
    '/usr/lib/electrum-btcq',
] + sys.path
sys.argv[0] = '$SCRIPT'
loader = importlib.machinery.SourceFileLoader('__main__', '$SCRIPT')
spec   = importlib.util.spec_from_loader('__main__', loader, origin='$SCRIPT')
mod    = importlib.util.module_from_spec(spec)
mod.__file__   = '$SCRIPT'
mod.__loader__ = loader
mod.__spec__   = spec
sys.modules['__main__'] = mod
spec.loader.exec_module(mod)
" "$@"
