#!/bin/sh

# Testing 1GB file now.

# Test writes on (unecrypted) ramdisk, so we're not seeing disk IO or
# local filesystem encryption latency.
DST=/run/user/1000

_test_gpg() {
    rm -f $DST/decrypted $DST/encrypted.FMT
    /usr/bin/time -v $GPG \
        --batch --symmetric --passphrase-file ./password.txt \
        --s2k-mode 3 --s2k-digest-algo SHA512 --s2k-count 65536 \
        --compress-algo none \
        --cipher-algo AES256 \
        --output $DST/encrypted.FMT original.txt 2>&1 |
        sed -e "s/^/ENC-${SUFFIX}: /" &&
    /usr/bin/time -v $GPG \
        --batch --decrypt --passphrase-file ./password.txt \
        --output $DST/decrypted $DST/encrypted.FMT 2>&1 |
        sed -e "s/^/DEC-${SUFFIX}: /" &&
    cmp original.txt $DST/decrypted || echo "FAILURE " >&2
}

test_gpg_1_4() { GPG=gpg1 SUFFIX=g1.4 _test_gpg; }
test_gpg_2_2() { GPG=gpg2 SUFFIX=g2.2 _test_gpg; }
test_gpg_2_3() { GPG=gpg2.3-O3 SUFFIX=g2.3 _test_gpg; }
test_gpg_2_3_no_aesni() {
    LD_PRELOAD=./gcrypt-no-aesni.so && export LD_PRELOAD
    GPG=gpg2.3-O3 SUFFIX=n2.3 _test_gpg preload
    unset LD_PRELOAD; }

_test_openssl_1_1_1() {
    rm -f $DST/decrypted $DST/encrypted.FMT
    /usr/bin/time -v openssl \
        enc -e -pass file:./password.txt \
        -pbkdf2 -md sha512 -iter 250 -salt \
        -aes-256-cbc \
        -out $DST/encrypted.FMT \
        -in original.txt 2>&1 |
        sed -e "s/^/ENC-${SUFFIX}: /" &&
    /usr/bin/time -v openssl \
        enc -d -pass file:./password.txt \
        -pbkdf2 -md sha512 -iter 250 -salt \
        -aes-256-cbc \
        -out $DST/decrypted \
        -in $DST/encrypted.FMT 2>&1 |
        sed -e "s/^/DEC-${SUFFIX}: /" &&
    cmp original.txt $DST/decrypted || echo "FAILURE " >&2
}

test_openssl_1_1_1() { SUFFIX=ossl _test_openssl_1_1_1; }
test_openssl_1_1_1_no_aesni() {
    OPENSSL_ia32cap="~0x200000200000000" && export OPENSSL_ia32cap
    SUFFIX=osno _test_openssl_1_1_1
    unset OPENSSL_ia32cap; }

test_customcrypt() {
    SUFFIX=cust
    rm -f $DST/decrypted $DST/encrypted.FMT
    /usr/bin/time -v \
        python3 customcrypt.py -e original.txt $DST/encrypted.FMT 2>&1 |
        sed -e "s/^/ENC-${SUFFIX}: /" &&
    /usr/bin/time -v \
        python3 customcrypt.py -d $DST/encrypted.FMT $DST/decrypted 2>&1 |
        sed -e "s/^/DEC-${SUFFIX}: /" &&
    cmp original.txt $DST/decrypted || echo "FAILURE " >&2
}

ITERATIONS=1
for x in `seq $ITERATIONS`; do
    echo "TIME: $(LC_ALL=C date)"; test_customcrypt
    echo "TIME: $(LC_ALL=C date)"; test_gpg_1_4
    echo "TIME: $(LC_ALL=C date)"; test_gpg_2_2
    echo "TIME: $(LC_ALL=C date)"; test_gpg_2_3
    echo "TIME: $(LC_ALL=C date)"; test_gpg_2_3_no_aesni
    echo "TIME: $(LC_ALL=C date)"; test_openssl_1_1_1
    echo "TIME: $(LC_ALL=C date)"; test_openssl_1_1_1_no_aesni
done
