#!/bin/bash

# Compatibility wrapper for kGraft / SLE 12
# Will be removed in future SLE releases
# Libor Pechacek <lpechacek@suse.com>

unset VERBOSE
unset VERBOSE_OPT

function kgr_poke_processes() {
    if [[ $EUID -ne 0 ]]; then
       echo "Warning: running as non-root user, only this user's processes will be poked" >&2
    fi

    for PROC in /proc/[0-9]*; do
	if [ 0$(cat $PROC/kgr_in_progress 2>/dev/null) -ne 0 ]; then
	    PID=$(echo $PROC | cut -d/ -f3)
	    if [ -n "$VERBOSE" ]; then
		echo "sending $PID STOP/CONT"
	    fi
	    kill -STOP $PID
	    # give kernel time to distribute the signal to all threads
	    sleep .1
	    kill -CONT $PID
	fi
    done
}

USAGE="Usage: $0 [-h][-v] COMMAND
Compatibility wrapper for migration from kGraft / SLE 12. Use klp(1) in new
applications. This wrappere will be removed in future SLE releases.

Commands:
        status:    display the overall status of kernel live patching
        patches:   display the list of loaded patches
        blocking:  list execution threads that are preventing kernel
                   live patching from finishing
        blocking_threads: (obsolete) same as blocking
        poke:      (obsolete) move forward with the kernel live patching by
                   sending STOP and CONT signal to the pending processes

Options:
	-h	   print this help
	-v	   more detailed output

Report bugs at https://bugzilla.suse.com/."
PKGVERSION="@@VERSION@@"

while getopts vh-: opt
do
    case $opt$OPTARG in
    -help|h)
	exec echo "$USAGE" ;;
    -version)
	exec echo "kgr $PKGVERSION" ;;
    v) VERBOSE=$((${VERBOSE:-0} + 1))
       VERBOSE_OPT="$VERBOSE_OPT -v";;
    *)
	echo "$0: try '$0 --help'" >&2; exit 1 ;;
    esac
done

shift `expr $OPTIND - 1`

if [ $# -ne 1 ]; then
    echo -e "Error: no command provided\n" >&2
    echo "$USAGE"
    exit 1
fi

case $1 in
    blocking) exec klp $VERBOSE_OPT blocking ;;
    blocking_threads) exec klp $VERBOSE_OPT blocking ;;
    poke) kgr_poke_processes ;;
    status) exec klp $VERBOSE_OPT status ;;
    check) exec klp $VERBOSE_OPT check ;;
    patches) exec klp $VERBOSE_OPT patches ;;
    *) echo "Error: unknown command \`$1'"; exit 1 ;;
esac

# vim: ai sw=4 et sts=4 ft=sh
