#!/bin/sh
# Mount compartments (all, or those named).
#
#   tools/unlock [c1 c2 ...]
#
# Asks for the vault code (ADR-007 §1); the unlock secret is decrypted on THIS machine.
# If CONTINUITY_REMOTE=user@host is set, it is streamed over SSH to gocryptfs
# on that server and never written to its disk (ADR-001 "Platform", ADR-002 §1).
# Mounts unmount themselves after $CONTINUITY_IDLE without use.
. "$(dirname "$0")/lib.sh"
need age
need_identity
first=$(compartments "$@" | head -n1)
check_code "$KEYS/$first.pass.age"

for c in $(compartments "$@"); do
    if [ -n "$CONTINUITY_REMOTE" ]; then
        unwrap "$KEYS/$c.pass.age" | ssh "$CONTINUITY_REMOTE" \
            "d=\"$CONTINUITY_REMOTE_DATA\"; mountpoint -q \"\$d/mnt/$c\" && exit 0; gocryptfs -q -i $CONTINUITY_IDLE -passfile /dev/stdin \"\$d/cipher/$c\" \"\$d/mnt/$c\"" \
            || die "could not unlock $c on $CONTINUITY_REMOTE"
    else
        need gocryptfs
        if is_mounted "$MNT/$c"; then say "$c already unlocked"; continue; fi
        unwrap "$KEYS/$c.pass.age" \
            | gocryptfs -q -i "$CONTINUITY_IDLE" -passfile /dev/stdin "$CIPHER/$c" "$MNT/$c" \
            || die "could not unlock $c"
    fi
    say "$c unlocked"
done
