#! /bin/sh
# Copyright (C) 2018 Cumulus Networks, Inc.
#
# Check to see if reboot will be needed based on packages to
# be installed, creating a policy-rc.d file if so.
# Invoked via an Dpkg::Pre-Install-Pkgs hook in /etc/apt/conf.d

policy=/usr/sbin/policy-rc.d

# Do not run hooks when cumulus-installer uses apt-get
# and do not overwrite an already existing policy script
[ -x $policy -o "$UPDATE_CUMULUS" = "No" ] && exit 0

mkdir -p /run/upgrade-services
echo Upgrading > /run/need-policy
reboot=0

# check to see if a reboot is likely to be required, primarily
# for debugging purposes.
while read pkg rest; do
	package=${pkg##*/}
	case "$package" in
	linux-image-*|cumulus-platform*) reboot=1 ;;
	platform-modules*|mlx-modules*|sx-sdk-eth*) reboot=1 ;;
	bcm-sdk*) # if bcm-sdk is being changed, mark switchd for restart
		echo switchd.service:start >> /run/upgrade-services/list
		;;
	esac
done

[ $reboot -eq 1 ] &&
	logger -t Policy -s "Reboot likely required" >> /run/need-policy 2>&1

cat > $policy << \EOF
#!/bin/sh
# Generated by apt-policy-rc-check
# Prevent service stop and start during upgrades that will require a reboot
# Created via an apt hook
[ -e /run/need-policy ] && {
	eval action=\${$#}; last=1
	case "$action" in # handle init.d scripts with run levels
	[0-6sS]) eval action=\${$(($#-1))} ; last=2 ;;
        esac
	case "$action" in
	*start|stop) # ignore others
	    # if multiple services, and 101, we only get the first
	    # but handle possible multiple service case
	    while [ $# -gt $last ]; do
		service="$1"
		shift
		case "$service" in
		--*) continue ;; # --quiet, etc.
		esac
		mkdir -p /run/upgrade-services
		echo "${service}:${action}" >> /run/upgrade-services/list
		logger -t Policy "Service ${service} action ${action} postponed"
	    done
            ;;
        esac
	exit 101
    }
# Safety net; if we have rebooted, we no longer need this script
rm -f /usr/sbin/policy-rc.d
exit 104
EOF

chmod 755 /usr/sbin/policy-rc.d
exit 0
