#!/usr/bin/env bats
# vim:set ft=sh:

load '/usr/lib/bats/bats-support/load.bash'
load '/usr/lib/bats/bats-assert/load.bash'
load "../helpers/common"

setup() {
    source "functions"
}

@test "tpm2 hook adds required binaries" {
    local buildroot
    buildroot="$(mktemp -d --tmpdir="$BATS_RUN_TMPDIR" "${BATS_TEST_NAME}.XXXXXX")"
    
    echo "HOOKS=(tpm2)" > "$buildroot/mkinitcpio.conf"
    
    run ./mkinitcpio \
        -D "${PWD}" \
        -c "$buildroot/mkinitcpio.conf" \
        -g "$buildroot/initramfs.img"
    
    assert_success
    [ -f "$buildroot/usr/bin/systemd-measure" ]
    [ -f "$buildroot/usr/bin/systemd-cryptenroll" ]
    [ -f "$buildroot/usr/bin/tpm2_createprimary" ]
    [ -f "$buildroot/usr/bin/tpm2_pcrread" ]
}

@test "tpm2 signature generation works" {
    local buildroot privkey pubkey
    buildroot="$(mktemp -d --tmpdir="$BATS_RUN_TMPDIR" "${BATS_TEST_NAME}.XXXXXX")"
    privkey="$(mktemp)"
    pubkey="$(mktemp)"
    
    # Generate test keys
    openssl genpkey -algorithm RSA -out "$privkey"
    openssl rsa -in "$privkey" -pubout -out "$pubkey"
    
    echo "HOOKS=(tpm2)" > "$buildroot/mkinitcpio.conf"
    
    TPM2_PRIVKEY="$privkey" TPM2_PUBKEY="$pubkey" TPM2_PCRS="0,2,4,7" \
        run ./mkinitcpio \
            -D "${PWD}" \
            -c "$buildroot/mkinitcpio.conf" \
            -g "$buildroot/initramfs.img"
    
    assert_success
    [ -f "$buildroot/pcrsig.json" ]
    [ -f "$buildroot/pcrpkey" ]
} 