#!/bin/bash
# Two gates before the daemon. Both protect the same thing: a Tang that starts
# without its keys is worse than a Tang that does not start.
#
#  1. The key directory must be on a mounted filesystem. In Tick that is the
#     LUKS vault, which a human unlocks after a reboot -- until then the mount
#     point is an empty directory on the root disk. tangd would happily serve
#     from it.
#  2. The key directory must not be empty. tangd advertises whatever keys it
#     finds; with none it answers with an empty advertisement, and every LUKS
#     volume bound to this Tang can no longer be opened. Worse, a later
#     tangd-keygen into the now-writable empty directory would create NEW keys
#     and make the old bindings invalid for good.
#
# s6 restarts this script, so the service comes up by itself once the vault is
# open -- nobody has to remember to start it. The sleep keeps that from being a
# hot loop. No .permafail here on purpose: waiting for a human to unlock the
# vault is a legitimate state, not a failure.
exec 2>&1

TANG_KEYDIR="/srv/vault/tang"
TANG_REQUIRE_MOUNT="/srv/vault"
TANG_WAIT="30"
[ -r ./data/default.env ] && . ./data/default.env
[ -r /etc/default/tang ] && . /etc/default/tang

if [ -n "${TANG_REQUIRE_MOUNT}" ] && ! mountpoint -q "${TANG_REQUIRE_MOUNT}"; then
  echo "tang: ${TANG_REQUIRE_MOUNT} is not mounted -- not starting, waiting ${TANG_WAIT}s"
  sleep "${TANG_WAIT}"
  exit 1
fi

if [ -z "$(ls -A "${TANG_KEYDIR}" 2>/dev/null)" ]; then
  echo "tang: ${TANG_KEYDIR} is empty -- not starting (keys missing), waiting ${TANG_WAIT}s"
  sleep "${TANG_WAIT}"
  exit 1
fi

exec run-script-daemon tang
