#!/usr/bin/env bash

build() {
    if ! pacman -Qi clevis >/dev/null 2>&1; then
        error "Package clevis not installed"
        return 1
    fi

    # check for optional dependencies to determine if tpm2 or tang unlocking
    # can be used:
    ## tang
    local has_curl=""
    pacman -Qi curl >/dev/null 2>&1 && has_curl=true
    ## tpm2
    local has_tpm2=""
    pacman -Qi tpm2-tools >/dev/null 2>&1 && has_tpm2=true

    if [[ ! "$has_curl" && ! "$has_curl" ]]; then
        error "Neither curl nor tpm2-tools installed. This will not work"
        return 1
    fi

    # make sure busybox (and thus sh) are present
    # (might have been already installed by some other hook, e.g. base)
    # (other busybox applets are added also because they allocate nearly no space in initramfs)
    if [[ ! -x "$BUILDROOT/usr/bin/busybox" ]]; then
        add_binary /usr/lib/initcpio/busybox /usr/bin/busybox
        local applet
        for applet in $(/usr/lib/initcpio/busybox --list); do
            add_symlink "/usr/bin/$applet" busybox
        done
    fi

    # common files
    add_binary bash
    add_binary jose
    add_binary cryptsetup
    add_binary grep /usr/local/bin
    add_binary tr

    # clevis
    add_binary clevis
    add_binary clevis-luks-common-functions
    add_binary clevis-luks-unlock
    add_binary clevis-decrypt
    add_binary clevis-decrypt-sss

    add_file /usr/lib/systemd/systemd-reply-password

    add_systemd_unit clevis-luks-askpass.service
    add_systemd_unit clevis-luks-askpass.path
    add_symlink /etc/systemd/system/sysinit.target.wants/clevis-luks-askpass.path \
                /usr/lib/systemd/system/clevis-luks-askpass.path

    # unlock with tang
    if [[ "$has_curl" ]]; then
        add_binary curl
        add_binary clevis-decrypt-tang
        add_file /etc/ssl/certs/ca-certificates.crt
    else
        warning "Package curl not installed. Unlocking with tang will not work"
    fi

    # unlock with tpm2
    if [[ "$has_tpm2" ]]; then
        add_binary tpm2_createprimary
        add_binary tpm2_load
        add_binary tpm2_unseal
        add_binary tpm2_flushcontext
        add_binary clevis-decrypt-tpm2
        add_full_dir /usr/lib libtss2-tcti-device.so
    else
        warning "Package tpm2-tools not installed. Unlocking with tpm2 will not work"
    fi

}

help() {
    cat <<__EOF_HELP__
This hook allows unlocking encrypted volumes (even root) with clevis. tang and
tpm2 bound volumes are supported. Mind that this hooks only works in
conjunction with sd-encrypt.
__EOF_HELP__
}

