#!/bin/sh
set -e

pkg=secrecy

export LC_ALL=C.UTF-8
if [ "${AUTOPKGTEST_TMP}" = "" ] ; then
  AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
  trap "rm -rf ${AUTOPKGTEST_TMP}" 0 INT QUIT ABRT PIPE TERM
fi

cd "${AUTOPKGTEST_TMP}"

set -v
################################################################################
# I. Test secrecy
# 0.  Preparation
	HOME="${AUTOPKGTEST_TMP}"
	export HOME
	cp -r /usr/share/doc/secrecy/* .
	gunzip *.gz
	readonly GPGID="autopkgtest@example.org"
	readonly EXPIRY="$(date +'%F' -d 'tomorrow + 1 hour')"
	gpg --batch  --pinentry-mode loopback  --passphrase '' \
		--quick-generate-key "$GPGID" default default "$EXPIRY"

# 1.  Create key
	readonly KEYNAME="autpkgtest_key"
	readonly KEYHASH="$( secrecy createKey AES256 "$GPGID" "$KEYNAME")"
	secrecy listKeys

# NOTE: Further secrecy tests were flaky from that point, so not running them
#       for the stable part of that autopkgtest script.

################################################################################
# II. Test libsecrecy-dev
# 0.  Preparation
	CXX="c++"
	CXXFLAGS="$( pkg-config libsecrecy --cflags )"
	LDFLAGS="$(  pkg-config libsecrecy --libs )"
	export CXXFLAGS LDFLAGS
	printf -- 'CXXFLAGS=%s\nLDFLAGS=%s\n' "$CXXFLAGS" "$LDFLAGS"

# 1.  Encryption program
	cat > encrypt.cpp <<-END
	#include <libsecrecy/GCMOutputStream.hpp>
	#include <iostream>

	int main()
	{
	        std::string const scipher = "AES256";
	        std::string const shexhash = "$KEYHASH";
	        static std::size_t const buffersize = 16*1024;
	        libsecrecy::GCMOutputStream GOS(std::cout, shexhash);
	        char B[buffersize];

	        while ( std::cin )
	        {
	                std::cin.read(&B[0],buffersize);
	                GOS.write(&B[0],std::cin.gcount());
	        }
	}
	END
	"$CXX" $CXXFLAGS -c encrypt.cpp -o encrypt.o
	"$CXX" $CXXFLAGS    encrypt.o   -o encrypt   $LDFLAGS
# NOTE: program execution flaky, so not tested in this stable pass.

# 2.  Decryption program
	cat > decrypt.cpp <<-END
	#include <libsecrecy/GCMInputStream.hpp>
	#include <iostream>

	int main()
	{
	        libsecrecy::GCMInputStream GIS(std::cin);
	        static std::size_t const buffersize = 16*1024;
	        char B[buffersize];

	        while ( GIS )
	        {
	                GIS.read(&B[0],buffersize);
	                std::cout.write(&B[0],GIS.gcount());
	        }
	}
	END
	"$CXX" $CXXFLAGS -c decrypt.cpp -o decrypt.o
	"$CXX" $CXXFLAGS    decrypt.o   -o decrypt   $LDFLAGS
# NOTE: program execution flaky, so not tested in this stable pass.

################################################################################
