#!/bin/sh
# Start a tor (with the network off) whose control port is a Unix socket
# with cookie authentication, as Debian's tor package sets it up, and check
# that tordnsel connects to it and authenticates.
set -eu
dir=$(mktemp -d)
tor_pid=
td_pid=
cleanup() {
  [ -n "$td_pid" ] && kill "$td_pid" 2>/dev/null || true
  [ -n "$tor_pid" ] && kill "$tor_pid" 2>/dev/null || true
  rm -rf "$dir"
}
trap cleanup EXIT
mkdir -m 700 "$dir/tor" "$dir/state" "$dir/run"
cat > "$dir/torrc" <<EOT
DataDirectory $dir/tor
ControlSocket $dir/tor/control GroupWritable RelaxDirModeCheck
SocksPort unix:$dir/tor/socks
CookieAuthentication 1
CookieAuthFileGroupReadable 1
CookieAuthFile $dir/tor/control.authcookie
DisableNetwork 1
Log notice stderr
EOT
tor -f "$dir/torrc" &
tor_pid=$!
for i in $(seq 60); do
  [ -S "$dir/tor/control" ] && [ -s "$dir/tor/control.authcookie" ] && break
  sleep 0.5
done

cat > "$dir/tordnsel.conf" <<EOT
ZoneOfAuthority exitlist.example.com.
DomainName exitlist-ns.example.com.
SOARName hostmaster.example.com.
StateDirectory $dir/state
RuntimeDirectory $dir/run
RunAsDaemon False
DNSListenAddress 127.0.0.1:15354
TorControlAddress unix:$dir/tor/control
TorSocksAddress unix:$dir/tor/socks
Log info file $dir/tordnsel.log
EOT
tordnsel -f "$dir/tordnsel.conf" &
td_pid=$!
for i in $(seq 60); do
  grep -q "Successfully initialized Tor controller connection" \
    "$dir/tordnsel.log" 2>/dev/null && break
  sleep 0.5
done
cat "$dir/tordnsel.log"
grep -q "Successfully initialized Tor controller connection" "$dir/tordnsel.log"
echo OK
