#!/bin/sh

# Exit immediately if a command exits with a non-zero status
set -e

# Summary of the script's functionality
summary="A tool that enables automatic decryption of ZFS rpools with TPM2"

# Display summary if requested
if [ "$1" = "--summary" ]; then
    echo "$summary"
    exit 0
fi

# Function to display usage information of zlevis
info() {
    exec >&2
    echo "Usage: \"zlevis {decrypt|encrypt} <pool>\""
    exit 2
}

# Function to display usage information of zlevis encrypt pool
encrypt_pool_info() {
    exec >&2
    echo "Usage: \"zlevis encrypt <pool> '{\"property\":\"value\"}' < file.key\""
    echo
    echo "This command uses the following configuration properties:"
    echo "  hash: <string> -> Hash algorithm used in the computation of the object name (default: sha256)."
    echo "  key: <string> -> Algorithm type for the generated key (default: ecc)."
    echo "  pcr_bank: <string> -> PCR algorithm bank to use for policy (default: first supported by TPM)."
    echo "  pcr_ids: <string> -> PCR list used for policy. If not present, no policy is used."
    echo "  pcr_digest: <string> -> Binary PCR hashes encoded in base64. If not present, the hash values are looked up."
    exit 2
}

# Determine the argument path and execute the relevant script or function
if [ -t 0 ]; then
    case "$1" in
        "decrypt") zfs list -Ho tpm:jwe "$2" | zlevis-decrypt;;
        "encrypt") encrypt_pool_info;;
        *) info;;
    esac
else
    case "$1" in
        "encrypt") read -r -d . key || zfs set tpm:jwe=$(printf "%s" "$key" | zlevis-encrypt "$3") "$2";;
        *) info;;
    esac
fi

# Exit with the status of the last command
exit $?