check_db_for_message() {
    local db="${1}"
    local message="${2}"
    local -i counter=10

    case "${db}" in
        mysql)
            dbname="Syslog"
            table="SystemEvents"
            cmd="mysql -uroot ${dbname} --batch -N -e \"SELECT COUNT(*) FROM ${table} WHERE trim(Message) = \\\"${message}\\\";\""
            ;;
        postgresql)
            dbname="Syslog"
            table="systemevents"
            cmd="sudo -u postgres -i  psql -At -d ${dbname} -c \"SELECT COUNT(*) FROM ${table} WHERE trim(message) = '${message}';\""
            ;;
        *)
            echo "Unrecognized db: ${db}"
            return 1
            ;;
    esac
    echo -n "Checking ${db} for the message (${counter} attempts): "
    while [ ${counter} -gt 0 ]; do
        count=$(eval "${cmd}")
        if [ ${count} -eq 1 ]; then
            echo
            echo "Message correctly found in the ${db} ${dbname}.${table} table"
            break
        else
            echo -n "."
            counter=$((counter-1))
            sleep 1s
            continue
        fi
    done
    if [ ${counter} -eq 0 ]; then
        echo
        echo "Failed to find message \"${message}\" in the ${db} ${dbname}.${table} table"
        return 1
    fi
}

try_enforce_apparmor() {
    local apparmor_profile="/etc/apparmor.d/usr.sbin.rsyslogd"
    local -i rc=0

    if [ ! -d /etc/apparmor.d/rsyslog.d ]; then
        echo "No /etc/apparmor.d/rsyslog directory, not touching apparmor status"

    elif [ ! -f "${apparmor_profile}" ]; then
        echo "No ${apparmor_profile} file, not touching apparmor status"

    elif ! aa-status --enabled 2>/dev/null; then
        echo "Apparmor disabled (aa-status)"

    else
        echo "Enforcing the ${apparmor_profile} apparmor profile"
        aa-enforce "${apparmor_profile}" || rc=$?
        if [ ${rc} -ne 0 ]; then
            # This can fail on armhf in the Ubuntu DEP8 infrastructure
            # because that environment restricts changing apparmor profiles.
            # (See LP: #2008393)
            arch=$(dpkg --print-architecture)
            vendor=$(dpkg-vendor --query Vendor)
            if [ "${arch}" = "armhf" ] && [ "${vendor}" = "Ubuntu" ]; then
                echo "WARNING: failed to enforce apparmor profile."
                echo "On armhf and Ubuntu DEP8 infrastructure, this is not a fatal error."
                echo "See #2008393 for details."
                rc=0
            else
                echo "ERROR: failed to enforce apparmor profile"
            fi
        fi
    fi
    return ${rc}
}
