#!/usr/bin/env atf-sh

. $(atf_get_srcdir)/test_env.sh
init_tests \
	abuild_sign_help \
	abuild_sign_invalid_opt \
	abuild_sign_missing_arg \
	abuild_sign_installed_missing \
	abuild_sign_installed_missing_pub \
	abuild_sign_installed_missing_priv \
	abuild_sign_installed \
	abuild_sign_owner_type_invalid \
	abuild_sign_owner_type_default \
	abuild_sign_owner_type_rsa \
	abuild_sign_owner_type_rsa256

export ABUILD_SHAREDIR="$(atf_get_srcdir)/.."
export ABUILD_USERDIR="$HOME"/.abuild

init_keys() {
	cp -Ra "$(atf_get_srcdir)"/testdata/.abuild "$PWD"
}

abuild_sign_help_body() {
	atf_check -s exit:0 \
		-o match:"Usage:" \
		abuild-sign --help
}

abuild_sign_invalid_opt_body() {
	atf_check -s exit:2 \
		-e match:"Usage:" \
		abuild-sign -INVALID
}

abuild_sign_missing_arg_body() {
	atf_check -s exit:2 \
		-e match:"Usage:" \
		abuild-sign
}

abuild_sign_installed_missing_body() {
	atf_check -s exit:1 \
		-e match:"No private key found" \
		abuild-sign --installed
}

abuild_sign_installed_missing_pub_body() {
	init_keys
	rm .abuild/*.rsa.pub
	atf_check -s exit:1 \
		-e match:"rsa.pub: File not found" \
		abuild-sign --installed
}

abuild_sign_installed_missing_priv_body() {
	init_keys
	rm .abuild/*.rsa
	atf_check -s exit:1 \
		-e match:"rsa: File not found" \
		abuild-sign --installed
}

abuild_sign_installed_body() {
	init_keys
	atf_check -s exit:0 \
		abuild-sign --installed
}

abuild_sign_owner_type_invalid_body() {
	init_keys
	atf_check -s exit:1 \
		-e match:"abuild-sign: supported types are RSA and RSA256" \
		abuild-sign -t DSA foo.tar.gz
}

abuild_sign_owner_type_default_body() {
	init_keys
	echo foo > .PKGINFO
	tar -zcf foo.tar.gz .PKGINFO || atf_fail "Failed to create unsigned test archive"

	atf_check -s exit:0 \
		-e match:"Signed" \
		abuild-sign foo.tar.gz

	atf_check -s exit:0 \
		-o match:"0/0.*\.SIGN\.RSA\." \
		tar -ztvf foo.tar.gz
}

abuild_sign_owner_type_rsa_body() {
	init_keys
	echo foo > .PKGINFO
	tar -zcf foo.tar.gz .PKGINFO || atf_fail "Failed to create unsigned test archive"

	atf_check -s exit:0 \
		-e match:"Signed" \
		abuild-sign -t RSA foo.tar.gz

	atf_check -s exit:0 \
		-o match:"0/0.*\.SIGN\.RSA\." \
		tar -ztvf foo.tar.gz
}

abuild_sign_owner_type_rsa256_body() {
	init_keys
	echo foo > .PKGINFO
	tar -zcf foo.tar.gz .PKGINFO || atf_fail "Failed to create unsigned test archive"

	atf_check -s exit:0 \
		-e match:"Signed" \
		abuild-sign -t RSA256 foo.tar.gz

	atf_check -s exit:0 \
		-o match:"0/0.*\.SIGN\.RSA256\." \
		tar -ztvf foo.tar.gz
}
