#!/bin/bash
#
# setup and teardown helpers for buildah test
#

function setup() {
    REGISTRY_FQIN=quay.io/libpod/registry:2

    AUTHDIR=/tmp/buildah-tests-auth.$$
    mkdir -p $AUTHDIR

    CERT=$AUTHDIR/domain.crt
    if [ ! -e $CERT ]; then
        openssl req -newkey rsa:4096 -nodes -sha256 \
                -keyout $AUTHDIR/domain.key -x509 -days 2 \
                -out $AUTHDIR/domain.crt \
                -subj "/C=US/ST=Foo/L=Bar/O=Red Hat, Inc./CN=localhost"
    fi

    if [ ! -e $AUTHDIR/htpasswd ]; then
        podman run --rm --entrypoint htpasswd $REGISTRY_FQIN \
               -Bbn testuser testpassword > $AUTHDIR/htpasswd
    fi

    podman run -d -p 5000:5000 \
           --name registry \
           -v $AUTHDIR:/auth:Z \
           -e "REGISTRY_AUTH=htpasswd" \
           -e "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm" \
           -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd \
           -e REGISTRY_HTTP_TLS_CERTIFICATE=/auth/domain.crt \
           -e REGISTRY_HTTP_TLS_KEY=/auth/domain.key \
           $REGISTRY_FQIN
}

function teardown() {
    podman rm -f registry
}