#!/bin/sh
# On install: write config from wizard answers, then unpack the bundled
# cryptography wheels (cp310/cp311/cp312) for the host's python ABI into
# the package's own var/pylib. No pip, no network, no root escalation —
# just stdlib zipfile extraction. The host's python3 must be 3.10–3.12.

VAR="/var/packages/aether-node/var"
TGT="/var/packages/aether-node/target"
PYLIB="${VAR}/pylib"
LOG="${VAR}/postinst.log"
mkdir -p "$VAR" "$PYLIB"

# Config — write on first install or wizard re-run; preserve on silent upgrade.
if [ -n "${mesh_token}" ]; then
    cat > "$VAR/config.env" <<EOF
MESH_TOKEN="${mesh_token}"
NODES="https://aether-us.ai-ministries.com,https://aether-uk.ai-ministries.com"
NODE_ID="${node_id:-nas-1}"
MAP_LABEL="${map_label:-NAS-NODE}"
MAX_GB="${max_gb:-5}"
SHARDS_DIR=""
EOF
elif [ ! -f "$VAR/config.env" ]; then
    cp "$TGT/conf/config.env.default" "$VAR/config.env"
fi

# Find python3.
PY=""
for p in \
    /var/packages/py3k/target/usr/local/bin/python3 \
    /usr/local/bin/python3 \
    /usr/bin/python3 \
    /opt/bin/python3 ; do
    [ -x "$p" ] && PY="$p" && break
done

if [ -z "$PY" ]; then
    echo "$(date) — no python3 found. Install SynoCommunity Python 3 then re-run package." >>"$LOG"
    exit 0   # don't fail install — user can fix and restart
fi

# Detect python minor version to pick the matching cp wheels.
PYVER="$("$PY" -c 'import sys;print(f"cp{sys.version_info.major}{sys.version_info.minor}")' 2>/dev/null)"
WHEELDIR="$TGT/wheels/$PYVER"

if [ ! -d "$WHEELDIR" ]; then
    echo "$(date) — bundled wheels for $PYVER not found ($WHEELDIR). Package supports cp310/cp311/cp312." >>"$LOG"
    exit 0
fi

# Wipe pylib and re-extract — fresh state every install/upgrade.
rm -rf "$PYLIB"/* 2>/dev/null
for whl in "$WHEELDIR"/*.whl ; do
    "$PY" -m zipfile -e "$whl" "$PYLIB" >>"$LOG" 2>&1
done
echo "$(date) — extracted wheels from $WHEELDIR into $PYLIB" >>"$LOG"

exit 0
