#!/bin/sh
#
# This script is called on first boot after a snapper rollback
# The purpose of this script is to verify that after a rollback
# the correct products are registered at SCC/SMT.

VARDIR="/var/lib/rollback"

if [ ! -f /etc/zypp/credentials.d/SCCcredentials ]; then
# We don't need to check anything if the system was not registered
  exit 0
fi

CURRENT_SNAPSHOT_ID=`grep subvol=/@/.snapshots/ /proc/mounts | grep "/ btrfs" | sed -e 's|.*.snapshots/\(.*\)/snapshot.*|\1|g'`
DEFAULT_SNAPSHOT_ID=`btrfs subvolume get-default / | sed -e 's|.*.snapshots/\(.*\)/snapshot|\1|g'`

# Make sure to trigger re-registration only when the system is running the
# production snapshot (i.e. don't trigger when the user selected some old
# snapshot from GRUB - or at least not until he made it the default one)
if [ "${CURRENT_SNAPSHOT_ID}" -ne "${DEFAULT_SNAPSHOT_ID}" ]; then
  exit 0
fi

# systemd does currently not support "Restart=" for oneshot services
# (https://github.com/systemd/systemd/issues/2582), so implement a manual
# retry algorithm
for i in {1..5}; do
  [ $i == 1 ] || sleep 2
  if SUSEConnect --rollback; then
    rm -f ${VARDIR}/check-registration
    exit 0
  fi
done
# If SUSEConnect never succeeds, quit with an error [bsc#1220680]
exit 1
