#!/bin/bash

source /usr/bin/next_boot_mount_point

SDK_BACKUP_DIR=/var/log/sdk_issu_backup
SDK_ISSU_GLOB="/var/issu* /var/port_map*"
UPGRADE_OR_ROLLBACK_FILE="/var/lib/cumulus/image-upgrade/upgrade-or-rollback"

function rebootOptions()
{
    local mountpoint="/mnt/next_partition"

    if [ -f $UPGRADE_OR_ROLLBACK_FILE ] && grep -q "rollback" $UPGRADE_OR_ROLLBACK_FILE;
    then
        echo "User is doing rollback. So, let us take the switch through cold reboot"

        rm -f $SDK_ISSU_GLOB

        # Clear the fast boot indication in the other partition so that
        # when the switch is booted from the other partition, it does not
        # think it is resuming ongoing Warmboot
        createMountPointForNextBootPartition $mountpoint
        echo "Clearing fast_boot flag in the next boot partition"
        echo "options sx_core fast_boot=0" > $mountpoint/etc/modprobe.d/sx.modprobe.conf

        /usr/sbin/reboot.real
    elif [ "$1" = "--fast" ]
    then
        echo "Fast boot" >> /var/tmp/boot_trace
        echo Backing up SDK ISSU files for later diagnositics
        mkdir -p $SDK_BACKUP_DIR
        rm -f $SDK_BACKUP_DIR/*
        for i in $SDK_ISSU_GLOB; do
            cp $i $SDK_BACKUP_DIR/
        done

        echo "Rebooting with kexec-tools for fastboot."
        echo "options sx_core fast_boot=1" > /etc/modprobe.d/sx.modprobe.conf
        ifdown mgmt
        /usr/lib/cumulus/kboot
    elif [ "$1" = "--help-fastboot" ]
    then
        echo "Fast boot help" >> /var/tmp/boot_trace
        echo "Use --fast option for fastboot with kexec"
    else
        echo "No Fast boot" >> /var/tmp/boot_trace
        rm -f $SDK_ISSU_GLOB
        echo "options sx_core fast_boot=0" > /etc/modprobe.d/sx.modprobe.conf
        /usr/sbin/reboot.real "$@"
    fi
}

# script #
sleep 2
rebootOptions $@
