#!/bin/sh
# Mangalord wrapper around dockurr/tor's tor binary.
#
# We bypass the image's stock entrypoint for two reasons:
#   1. It generates a `ControlPort 9051` line that binds to localhost
#      only (tor's default), but our backend lives in a separate
#      container and needs to reach 0.0.0.0:9051.
#   2. It then *skips* writing HashedControlPassword whenever the
#      user's torrc declares a ControlPort, so we can't both bind to
#      0.0.0.0 and benefit from its auto-hashing — it's one or the
#      other. Doing the hashing ourselves is simpler than threading
#      around its logic.
#
# This wrapper hashes $PASSWORD with `tor --hash-password`, appends a
# `HashedControlPassword` line to a writable copy of /etc/tor/torrc,
# then execs tor. Container runs as root (image default); tor binds
# 9050/9051 which don't require root and is fine inside a single-
# purpose container.

set -eu

if [ -z "${PASSWORD:-}" ]; then
    echo "ERROR: PASSWORD env must be set (the plain string the backend will" >&2
    echo "       send as CRAWLER_TOR_CONTROL_PASSWORD)" >&2
    exit 1
fi

# `tor --hash-password` prints the hash on the last line of stdout
# (preceded by initialization noise).
HASH=$(tor --hash-password "$PASSWORD" 2>/dev/null | tail -n1)
if [ -z "$HASH" ]; then
    echo "ERROR: 'tor --hash-password' produced no output" >&2
    exit 1
fi

# /etc/tor/torrc is bind-mounted read-only, so copy + append.
cp /etc/tor/torrc /tmp/torrc
printf '\n# Injected by mangalord-entrypoint.sh from $PASSWORD env.\nHashedControlPassword %s\n' "$HASH" >> /tmp/torrc

exec tor -f /tmp/torrc
