#!/bin/sh
# Start the RAM-only record index for continuity.service (ADR-006 §2). Runs as root, from
# ExecStartPre. Install as /opt/continuity/bin/index-start.
#
# PostgreSQL in a container, data on tmpfs, on 127.0.0.1:5437, with a NEW random password
# every start: other users on a shared server can reach loopback ports, and the index holds
# plaintext while the vault is open. The password exists only under /run/continuity/.
set -eu

. /etc/continuity/continuity.env
: "${CONTINUITY_DATA:?set in /etc/continuity/continuity.env}"
run=/run/continuity
engine=${CONTINUITY_CONTAINER:-$(command -v podman || command -v docker || true)}
[ -n "$engine" ] || { echo "continuity: neither podman nor docker is installed" >&2; exit 1; }

# The app is useless while c1 is locked. Read the mount table only: root cannot stat a FUSE
# mount made without allow_other, which is how the vault is mounted (ADR-001).
if ! awk -v m="$CONTINUITY_DATA/mnt/c1" '$2 == m { found = 1 } END { exit !found }' /proc/self/mounts; then
    echo "continuity: the vault is locked. Unlock it first, from your own computer: tools/start" >&2
    exit 1
fi

umask 077
pw=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')
# For the container (root only) and for the app (the continuity user only).
printf 'POSTGRES_PASSWORD=%s\n' "$pw" > "$run/index.pg.env"
printf 'CONTINUITY_INDEX_PASSWORD=%s\n' "$pw" > "$run/index.env"
chown continuity: "$run/index.env"
chmod 0400 "$run/index.env"

"$engine" rm -f continuity-index >/dev/null 2>&1 || true
"$engine" run -d --rm --name continuity-index \
    -e POSTGRES_DB=continuity -e POSTGRES_USER=continuity --env-file "$run/index.pg.env" \
    -p 127.0.0.1:5437:5432 --tmpfs /var/lib/postgresql:rw,size=512m \
    "${CONTINUITY_INDEX_IMAGE:-docker.io/library/postgres:18-alpine}" >/dev/null
rm -f "$run/index.pg.env"

i=0
until "$engine" exec continuity-index pg_isready -q -h 127.0.0.1 -U continuity; do
    i=$((i + 1))
    [ "$i" -lt 60 ] || { echo "continuity: the index did not start" >&2; exit 1; }
    sleep 1
done
