#!/bin/bash
#
# Copyright (C) 2021 Red Hat Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

set -euo pipefail

. ${KOLA_EXT_DATA}/libtest.sh

set -x

libtest_prepare_offline
libtest_enable_repover 0
cd $(mktemp -d)

case "${AUTOPKGTEST_REBOOT_MARK:-}" in
"")
rpm-ostree deploy --ex-cliwrap=true
/tmp/autopkgtest-reboot 1
;;

1)
wrapdir="/usr/libexec/rpm-ostree/wrapped"
if ! test -d "${wrapdir}"; then
    fatal "Missing ${wrapdir}"
fi
# Test wrapped functions for rpm
rpm --version
rpm -qa > /dev/null
rpm --verify bash >out.txt
assert_file_has_content out.txt "rpm --verify is not necessary for ostree-based systems"
rm -f out.txt
if rpm -e bash 2>out.txt; then
    fatal "rpm -e worked"
fi
assert_file_has_content out.txt 'Dropping privileges as `rpm` was executed with not "known safe" arguments'

if env -u INVOCATION_ID dracut 2>out.txt; then
    fatal "dracut worked"
fi
assert_file_has_content out.txt 'This system is rpm-ostree based'
rm -f out.txt
echo "ok cliwrap rpm + dracut"

yum -y install foo
rpm -q foo

# This is also exposed; currently we seem to not error out if it'd be a no-op
dnf image apply-live

echo "ok cliwrap yum install"

rpm-ostree deploy --ex-cliwrap=false
rpm-ostree apply-live --allow-replacement
rpm --version
rpm -qa >/dev/null
rpm --verify bash >out.txt || true
assert_not_file_has_content "ostree-based"
echo "ok cliwrap undo"
;;

*) echo "unexpected mark: ${AUTOPKGTEST_REBOOT_MARK}"; exit 1;;
esac
