#!/bin/bash
#==============================================================
#
#  Abs:  Utility to update/revert ipxe to patched buildroot version
#
#  Name: upgrade_cpu.sh
#
#  Side: Must be run on prod server corresponding to CPU
#
#  Facility: SLAC Controls
#
#  Auth: 08-Dec-2023, A. Le           (anle)
#--------------------------------------------------------------
#  Mod:
#        12-Dec-2023, A. Le           (anle)
#         Verify that destination buildroot version exists
#         Change 'CentOS 7' to 'CentOS'
#         Add option to view CPU info differences
#         Fix incorrect boot directories
#         Open tkdiff in background
#
#==============================================================
#

linuxRT_boot_dir=$TFTPBOOT/linuxRT/boot
centos_boot_dir=$TFTPBOOT/boot
set_vers_regex='^\s*set\s+vers\s+'
buildroot_regex='(?:[^#\s]+(?=-[^\d])|[^#\s]+)'
arch_regex='-[^#\s]+'
new_vers_suffix=-2

show_usage() {
    echo "Update/revert buildroot version of a CPU"
    echo "Usage: $0 cpu_name command"
    echo ""
    echo "Positional arguments:"
    echo "  cpu_name       The CPU nodename, e.g., cpu-b34-pm01"
    echo "  command        Specify 'upgrade' to update CPU buildroot version,"
    echo "                         'revert' to roll back, or"
    echo "                         'diff' to view differences in CPU info"
    echo "                           before and after upgrading"
}

# Parse CPU and command
if [ "$#" -ne 2 ]; then
    show_usage
    exit 1
fi
cpuname=$1
command=$2

# If command is diff, display differences in CPU info before and after upgrade
before_log=$IOC_DATA/$cpuname/cpu_info.before
after_log=$IOC_DATA/$cpuname/cpu_info.after
if [ "$command" = "diff" ]; then
    # Make sure cpu_info.before exists
    if [ ! -f "$before_log" ]; then
        echo "Error: $before_log does not exist. Please run 'cpu_info.sh $cpuname -b' before upgrading the CPU"
        exit 1
    fi

    # Make sure cpu_info.after exists
    if [ ! -f "$after_log" ]; then
        echo "Error: $after_log does not exist. Please run 'cpu_info.sh $cpuname -a' after upgrading and restarting the CPU"
        exit 1
    fi

    # Show differences
    tkdiff "$IOC_DATA/$cpuname/cpu_info.before" "$IOC_DATA/$cpuname/cpu_info.after" &
    exit 0
fi

# Look for its ipxe file in $TFTPBOOT/linuxRT/boot/ipxe
linuxRT_ipxe_file=$linuxRT_boot_dir/ipxe/$cpuname.ipxe
centos_ipxe_file=$centos_boot_dir/ipxe/$cpuname.ipxe
if [ -f "$centos_ipxe_file" ]; then
    boot_dir=$centos_boot_dir
    ipxe_file=$centos_ipxe_file
    echo "$cpuname is a CentOS CPU"

# If not found, search in $TFTPBOOT/boot/ipxe
elif [ -f "$linuxRT_ipxe_file" ]; then
    boot_dir=$linuxRT_boot_dir
    ipxe_file=$linuxRT_ipxe_file
    echo "$cpuname is a LinuxRT CPU"

# If still not found, return error
else
    echo "Error: $cpuname is neither a LinuxRT nor CentOS CPU on $IOCCONSOLE_ENV"
    exit 1
fi

# Find current buildroot version
read -r curr_vers arch <<<"$(perl -ne '/'"$set_vers_regex($buildroot_regex)($arch_regex)*"'/ && print "$1 $2"' "$ipxe_file")"
echo "Current buildroot version is $curr_vers$arch"

# If command is upgrade:
if [ "$command" = "upgrade" ]; then
    # If version already ends in -2, return already upgraded
    if [[ $curr_vers == *"$new_vers_suffix" ]]; then
        echo "Error: $cpuname has already been upgraded"
        exit 1
    fi

    # Else add -2 to get new version
    new_vers=$curr_vers$new_vers_suffix
    echo "New buildroot version is $new_vers$arch"

    # Make sure new version exists in TFTPBOOT
    if [ ! -d "$boot_dir/$new_vers$arch" ]; then
        echo "Error: $new_vers$arch does not exist in $boot_dir"
        exit 1
    fi

    # Confirm new version
    read -r -p "Confirm upgrade? [y/N] " response
    if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
        echo "Upgrading $cpuname..."
        perl -pi -e "s/($set_vers_regex)$buildroot_regex($arch_regex)*/\1$new_vers\2/" "$ipxe_file"
    else
        echo "Aborted"
        exit 1
    fi

# Else if command is revert:
elif [ "$command" = "revert" ]; then
    # If version doesn't end in -2, return not upgraded
    if [[ $curr_vers != *"$new_vers_suffix" ]]; then
        echo "Error: $cpuname has not been upgraded"
        exit 1
    fi

    # Else remove -2 to get old version
    old_vers=${curr_vers%"$new_vers_suffix"}
    echo "Old buildroot version is $old_vers$arch"

    # Make sure old version exists in TFTPBOOT
    if [ ! -d "$boot_dir/$old_vers$arch" ]; then
        echo "Error: $old_vers$arch does not exist in $boot_dir"
        exit 1
    fi

    # Confirm old version
    read -r -p "Confirm revert? [y/N] " response
    if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
        echo "Reverting $cpuname..."
        perl -pi -e "s/($set_vers_regex)$buildroot_regex($arch_regex)*/\1$old_vers\2/" "$ipxe_file"
    else
        echo "Aborted"
        exit 1
    fi

# Else return invalid command
else
    echo "Error: command must be 'upgrade' or 'revert'"
    exit 1
fi

# Finish
echo "Completed"
