#!/bin/sh
# Administrative launcher. Mounts and keys are managed by the OS, not this script.
set -eu
export LC_ALL=C
die() { printf 'schipsave-protected: %s\n' "$*" >&2; exit 2; }
[ "$#" -ge 6 ] || die 'uso: schipsave-protected zfs|luks|fs IDENTIDADE MOUNT -- COMANDO REPO ...'
kind=$1 identity=$2 mount=$3
[ "$4" = -- ] || die 'separador -- ausente'
shift 4
case "$mount" in /*) ;; *) die 'mount deve ser absoluto' ;; esac
mount=$(realpath -e -- "$mount") || die 'mount indisponível'
mount_id=$(findmnt -rn -M "$mount" -o ID) || die 'volume não montado no ponto esperado'
case "$mount_id" in ''|*[!0-9]*) die 'montagem ambígua' ;; esac
case "$kind" in
    fs)
        case "$identity" in ''|*[!a-zA-Z0-9-]*) die 'UUID filesystem inválido' ;; esac
        [ "$(findmnt -rn -M "$mount" -o UUID)" = "$identity" ] || die 'UUID filesystem diferente do esperado'
        ;;
    zfs)
        [ "$(findmnt -rn -M "$mount" -o FSTYPE)" = zfs ] || die 'filesystem não é ZFS'
        [ "$(findmnt -rn -M "$mount" -o SOURCE)" = "$identity" ] || die 'dataset diferente do esperado'
        encryption=$(zfs get -H -o value encryption "$identity") || die 'não foi possível consultar encryption'
        case "$encryption" in
            off) ;; # Native repository encryption does not require ZFS encryption.
            aes-128-ccm|aes-192-ccm|aes-256-ccm|aes-128-gcm|aes-192-gcm|aes-256-gcm)
                [ "$(zfs get -H -o value keystatus "$identity")" = available ] || die 'chave ZFS indisponível' ;;
            *) die 'criptografia ZFS não reconhecida' ;;
        esac
        ;;
    luks)
        uuid=$(printf '%s' "$identity" | tr 'A-F' 'a-f' | tr -d '-')
        case "$uuid" in ''|*[!0-9a-f]*) die 'UUID LUKS inválido' ;; esac
        [ "${#uuid}" = 32 ] || die 'UUID LUKS inválido'
        device=$(findmnt -rn -M "$mount" -o MAJ:MIN) || die 'dispositivo indisponível'
        case "$device" in ''|*[!0-9:]*) die 'dispositivo inválido' ;; esac
        dm_uuid=$(cat "/sys/dev/block/$device/dm/uuid") || die 'filesystem deve estar diretamente sobre o mapeamento LUKS'
        case "$dm_uuid" in CRYPT-LUKS1-"$uuid"-*|CRYPT-LUKS2-"$uuid"-*) ;; *) die 'mapeamento não é o LUKS esperado' ;; esac
        ;;
    *) die 'tipo deve ser zfs, luks ou fs' ;;
esac
# Administration may use its own ZFS dataset outside repository paths.
# All other submounts (including bind mounts inside a repository) are refused.
admin_mount_id=
if [ "$kind" = zfs ] && admin_mount_id=$(findmnt -rn -M "$mount/admin" -o ID); then
    case "$admin_mount_id" in ''|*[!0-9]*) die 'montagem admin ambígua' ;; esac
    [ "$(findmnt -rn -M "$mount/admin" -o FSTYPE)" = zfs ] || die 'admin deve ser ZFS'
    [ "$(findmnt -rn -M "$mount/admin" -o SOURCE)" = "$identity/admin" ] || die 'dataset admin diferente do esperado'
    [ "$(zfs get -H -o value sync "$identity/admin")" = standard ] || die 'admin requer sync=standard'
    [ "$(zfs get -H -o value encryption "$identity/admin")" = "$encryption" ] || die 'criptografia admin diferente do volume'
    if [ "$encryption" != off ]; then
        [ "$(zfs get -H -o value encryptionroot "$identity/admin")" = "$(zfs get -H -o value encryptionroot "$identity")" ] || die 'raiz criptográfica admin diferente'
        [ "$(zfs get -H -o value keystatus "$identity/admin")" = available ] || die 'chave admin indisponível'
    fi
else
    admin_mount_id=
fi
findmnt -Rrn -M "$mount" -o ID | while IFS= read -r child; do
    case "$child" in "$mount_id"|"$admin_mount_id") ;; *) die 'use volume dedicado sem montagens internas não autorizadas' ;; esac
done
# Resolve symlinks and compare mount IDs, including existing ancestors of new
# repository paths. A nested unencrypted mount on the same pathname is refused.
protected_path() {
    resolved=$(realpath -m -- "$1") || die 'caminho inválido'
    case "$resolved" in "$mount"|"$mount"/*) ;; *) [ "$mount" = / ] || die "caminho fora do volume: $1" ;; esac
    ancestor=$resolved
    while [ ! -e "$ancestor" ]; do ancestor=$(dirname -- "$ancestor"); done
    [ "$(findmnt -rn -T "$ancestor" -o ID)" = "$mount_id" ] || die "caminho em outra montagem: $1"
}
if [ "$1" = --lock-wait ]; then
    [ "$#" -ge 4 ] || die 'lock-wait requer segundos, comando e repositório'
    SCHIPSAVE_LOCK_WAIT=$2; export SCHIPSAVE_LOCK_WAIT; shift 2
fi
case "$1" in
    --check|job-state-update|job-state-info|storage-info|wal-archive|wal-cleanup|wal-cleanup-inbox|wal-receive|wal-queue-info|wal-queue-cancel|wal-recover-outbox|init|encryption|compression|profile|concurrency|compact|backup|capture|serve|serve-shared|stream-query-scoped|catalog|windows-metadata|restore|read-stream|restore-at|restore-latest|restore-postgresql|mount|mount-at|mount-period|prune|prune-zfs|prune-postgresql|check-postgresql|plan-postgresql|expire-postgresql|hold|immutability|seal-zfs|seal-prune|check-age|replicate|delete|discard-upload|info|list|stats|verify|repair) ;;
    *) die 'comando local de repositório não reconhecido (push deve proteger o servidor separadamente)' ;;
esac
[ "$#" -ge 2 ] || die 'repositório ausente'
protected_path "$2"
if [ "$1" = wal-cleanup ] || [ "$1" = wal-cleanup-inbox ]; then
    [ "$#" = 5 ] || [ "$#" = 6 ] || die 'wal-cleanup requer archive, staging, recibo e JOB_LOCK'
    protected_path "$3"
    protected_path "$4"
    protected_path "$5"
fi
if [ "$1" = expire-postgresql ] && [ "$#" = 8 ] && { [ "$7" = --receipt ] || [ "$7" = --outbox ]; }; then
    protected_path "$8"
fi
if [ "$1" = wal-recover-outbox ]; then protected_path "$3"; fi
if [ "$1" = replicate ]; then
    [ "$#" = 3 ] || die 'replicate requer origem e destino'
    protected_path "$3"
fi
umask 077
runtime="$mount/.schipsave-runtime-$(id -u)"
for directory in "$runtime" "$runtime/tmp" "$runtime/cache"; do
    protected_path "$directory"
    [ ! -L "$directory" ] || die 'diretório de runtime não pode ser link simbólico'
    if [ ! -e "$directory" ]; then mkdir -m 700 -- "$directory"; fi
    [ -d "$directory" ] && [ "$(stat -c %u -- "$directory")" = "$(id -u)" ] &&
        [ "$(stat -c %a -- "$directory")" = 700 ] || die 'runtime deve pertencer ao usuário e ter modo 0700'
done
export SCHIPSAVE_TMPDIR="$runtime/tmp" SCHIPSAVE_CACHE_DIR="$runtime/cache"
ulimit -c 0
binary=${SCHIPSAVE_BIN:-/usr/bin/schipsave}
[ "$("$binary" --scratch-policy-version)" = 1 ] || die 'binário sem suporte à política de temporários (requer 0.18+)'
[ "$1" != --check ] || exit 0
exec "$binary" "$@"
