#!/bin/bash
#
# Copyright (C) 2024 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

cd $(mktemp -d)

service=rpm-ostree-fix-shadow-mode.service
stamp=/etc/.rpm-ostree-shadow-mode-fixed2.stamp

case "${AUTOPKGTEST_REBOOT_MARK:-}" in
"")

libtest_prepare_fully_offline
libtest_enable_repover 0

systemctl status ${service} || true
rm -vf /etc/.rpm-ostree-shadow-mode*
chmod 0644 /etc/gshadow

# Verify running the service once fixes things
systemctl restart $service
assert_has_file "${stamp}"
assert_streq "$(stat -c '%f' /etc/gshadow)" 8000

# Now *undo* the fix, so that the current (then old) deployment
# is broken still, and ensure after reboot that it's fixed
# in both.

chmod 0644 /etc/gshadow
rm -vf /etc/.rpm-ostree*

booted_commit=$(rpm-ostree status --json | jq -r '.deployments[0].checksum')
ostree refs ${booted_commit} --create vmcheck2
rpm-ostree rebase :vmcheck2

/tmp/autopkgtest-reboot "1"
;;
"1")

systemctl status $service
assert_has_file "${stamp}"

verified=0
for f in $(ls /ostree/deploy/*/deploy/*/etc/{,g}shadow{,-}); do
    verified=$(($verified + 1))
    assert_streq "$(stat -c '%f' $f)" 8000
    echo "ok ${f}"
done
assert_streq "$verified" 8

journalctl -b -u $service --grep="Adjusted shadow files in deployment" | tee out.txt
assert_streq "$(wc -l < out.txt)" 2

echo "ok shadow"

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

esac
