#!/bin/sh

backup() {
    if [ ! -e test/helpers/tls-key.pem.orig ]; then
	cp -a test/helpers/tls-key.pem test/helpers/tls-key.pem.orig
    fi
    if [ ! -e test/helpers/tls-csr.pem.orig ]; then
	cp -a test/helpers/tls-csr.pem test/helpers/tls-csr.pem.orig
    fi
    if [ ! -e test/helpers/tls-cert.pem.orig ]; then
	cp -a test/helpers/tls-cert.pem test/helpers/tls-cert.pem.orig
    fi
}

restore() {
    if [ -e test/helpers/tls-key.pem.orig ]; then
	mv test/helpers/tls-key.pem.orig test/helpers/tls-key.pem
    fi
    if [ -e test/helpers/tls-csr.pem.orig ]; then
	mv test/helpers/tls-csr.pem.orig test/helpers/tls-csr.pem
    fi
    if [ -e test/helpers/tls-cert.pem.orig ]; then
	mv test/helpers/tls-cert.pem.orig test/helpers/tls-cert.pem
    fi
}

generate1() {
    openssl genrsa -out test/helpers/tls-key.pem 4096
    openssl req -new -subj /C=AU/ST=Some-State/O="Internet Widgits Pty Ltd"/CN=localhost -key test/helpers/tls-key.pem -out test/helpers/tls-csr.pem
    openssl req -in test/helpers/tls-csr.pem -x509 -nodes -key test/helpers/tls-key.pem -out test/helpers/tls-cert.pem -days 10 -sha256
}

case "$1" in
    patch)
	backup
	generate1
    ;;

    unpatch)
	restore
    ;;
esac
