#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
# SPDX-FileCopyrightText: 2021 Harald Sitter <sitter@kde.org>

skip="no"
if plymouth --ping; then
  TXT0="Preparing system update..."
  TXT1="keys:press 'c' to cancel" # keys: is a special behavior hack we have in breeze-plymouth, putting it in a special label
  plymouth display-message --text="$TXT0"
  plymouth display-message --text="$TXT1"
  timeout -s KILL 10s plymouth watch-keystroke --keys="cC"
  if [ "$?" = "0" ]; then # timeout=1, keystroke=0
    skip="yes"
  fi
  plymouth hide-message --text="$TXT1"
else
  # prompting without plymouth is hella horrible, abuse systemd's password helper as stand-in for plymouth.
  # Unlike plymouth we need to check the input in some form or fashion though
  out=$(systemd-ask-password --echo --timeout=10 "Enter 'c' and hit enter to cancel system update...")
  if [ "$out" = "" ]; then
    # we do not actually care greatly about the input so long as it is not empty. hitting enter isn't really
    # indicative of anything. could mean go away, could mean hurry up. who's to say.
    # $out consequently ought only be empty if the timeout was hit or the user hit enter without input
    skip="no"
  else
    skip="yes"
  fi
fi

if [ "$skip" = "no" ]; then
  echo "Continuing with update"
  exit 0
fi

echo "Update cancelled."

# undo systemd-system-update-generator and isolate into the real default.target
# NB: /system-update must be removed! It is the file systemd-system-update-generator triggers on,
#   leaving it behind would mean the daemon-reload again runs the generator and sets
#   system-update.target as default.target effectively looping back in on the current state of affairs.
rm -fv /system-update
rm -fv /run/systemd/generator.early/default.target
systemctl daemon-reload
# This needs removing or discover gets confused as it only looks at the PK marker, not
# the systemd marker file (which is a symlink to the PK one, mind you).
rm -fv /var/lib/PackageKit/offline-update-action

echo "Isolating into default.target ($(systemctl get-default)) instead..."
systemctl isolate --no-block default.target
