#!/bin/sh

if test "$1" != "sendmail" -a "$1" != "postfix" ; then
    echo "Usage: $0 sendmail|postfix buster|rocky8|rocky9|rocky10|bullseye|bookworm|jammy|noble|trixie"
    exit 1
fi
if test "$2" != "trixie" -a "$2" != "jammy" -a "$2" != "noble" -a "$2" != "buster" -a "$2" != "rocky8" -a "$2" != "bullseye" -a "$2" != "bookworm" -a "$2" != "rocky9" -a "$2" != "rocky10" ; then
    echo "Usage: $0 sendmail|postfix buster|rocky8|rocky9|rocky10|bullseye|bookworm|jammy|noble|trixie"
    exit 1
fi

MTA="$1"
OS="$2"
PULL=0
IMAGE=mm-$MTA-$OS-image
CONTAINER=mm-$MTA-$OS
if test "$3" = "pull" ; then
    PULL=1
    IMAGE=dskoll/$IMAGE
fi


bailout () {
    echo "FATAL: $@"
    exit 1
}

# Get version
VERSION=`grep '^PACKAGE_VERSION=' ../configure | sed -e 's/PACKAGE_VERSION=//' -e "s/'//g"`

if test -z "$VERSION" ; then
    bailout "Could not determine Mailmunge version!"
fi

# If host system is Debian and is using an HTTP proxy, copy that info
# to image
PROXY=`apt-config dump | grep Acquire::http::Proxy 2> /dev/null`
# Check if image exists
docker images | grep "^$IMAGE " > /dev/null 2>&1
if test $? = 0 ; then
   echo "Image $IMAGE appears to exist; skipping build."
   echo "If you wish to rebuild, please remove $IMAGE first."
else
    if test "$PULL" = "1" ; then
        docker pull $IMAGE || bailout "docker pull failed"
    else
        # Proxy fails for Ubuntu for some reason.
        if test "$PROXY" = "" -o "$OS" = "jammy" -o "$OS" = "noble"; then
            docker build -t "$IMAGE" -f "Dockerfile.$OS.$MTA" . || bailout "docker build failed"
        else
            docker build --build-arg "APT_PROXY=$PROXY" -t "$IMAGE" -f "Dockerfile.$OS.$MTA" . || bailout "docker build failed"
        fi
    fi
fi

docker container inspect "$CONTAINER" > /dev/null 2>&1
if test $? = 0 ; then
    echo "Container $CONTAINER appears to exist; skipping create."
    echo "If you wish to re-create, please remove container $CONTAINER first."
else
    # Create the container
    docker create --tmpfs /run --tmpfs /tmp "--name=$CONTAINER" "$IMAGE" || bailout "docker create failed"
fi


# If container is not running, start it
docker container inspect "$CONTAINER" 2>&1 | grep '"Running": false' > /dev/null 2>&1
if test $? = 0 ; then
    echo "Container $CONTAINER is not running; starting it..."
    docker start "$CONTAINER" || bailout "docker start failed"
else
    echo "Container $CONTAINER appears to be running."
fi

docker exec "$CONTAINER" /root/docker-testfiles/setup-tests.sh || bailout "docker exec failed"

exit 0
