#!/bin/sh
set -e

cleanup() {
    result=$?
    if [ ${result} -ne 0 ]; then
        echo "## Something failed"
        echo
        echo "## openssh packages installed:"
        dpkg -l | grep openssh
        echo
        echo "## contents of /etc/ssh:"
        ls -la /etc/ssh
        echo
    else
        echo "## Test passed"
    fi
    rm -f "${PURGE_LOG}"
}

trap cleanup EXIT

# Packages to install first; they take over the config of PURGE_PKGS
COUNTERPART_PKGS="openssh-client openssh-server"
# Packages expected to be in rc state, then purged.
PURGE_PKGS="openssh-client-gssapi openssh-server-gssapi"
SKIP_SUFFIX="-gssapi"
# Canary files that must survive the purge
CANARY_CONFIG_FILES="ssh_config sshd_config ssh_host_ed25519_key ssh_known_hosts"
PURGE_LOG=$(mktemp /tmp/purge.log.XXXXXX)

echo "## Installing counterpart packages: ${COUNTERPART_PKGS}"
apt-get -y install ${COUNTERPART_PKGS}
echo

for pkg in ${PURGE_PKGS}; do
    echo "## Checking that ${pkg} is in rc state"
    dpkg -l "${pkg}" | grep -E "^rc[[:blank:]]+${pkg} " || {
        echo "## ${pkg} is not in rc state"
        exit 1
    }
    echo
done

# the client's postrm purges this
echo "localhost ssh-ed25519 AAAA" > /etc/ssh/ssh_known_hosts

echo "## Purging ${PURGE_PKGS}"
apt-get -y purge ${PURGE_PKGS} | tee "${PURGE_LOG}"
echo

for pkg in $PURGE_PKGS; do
    echo "## Checking that the ${pkg} postrm skipped the purge"
    grep "${pkg%%$SKIP_SUFFIX} is installed; doing nothing" "${PURGE_LOG}"
    echo
    echo "## Checking that the ${pkg} package is uninstalled"
    dpkg -l | grep "${pkg} " && {
        echo "## ${pkg} is not uninstalled"
        exit 1
    } || :
    echo
done

for f in $CANARY_CONFIG_FILES; do
    echo "## Checking that /etc/ssh/${f} still exists"
    ls -la "/etc/ssh/${f}"
    echo
done
