#!/bin/bash
#==============================================================
#
#  Abs:  Display IOC-related information for a CPU
#
#  Name: cpu_info.sh
#
#  Side: Must be run on prod server corresponding to CPU
#
#  Facility: SLAC Controls
#
#  Auth: 08-Dec-2023, J. Katzung           (katzung)
#--------------------------------------------------------------
#  Mod:
#        12-Dec-2023, J. Katzung           (katzung)
#         ssh with StrictHostKeyChecking=no to avoid ssh credential conflicts
#        12-Dec-2023, A. Le                (ANLE):
#         Sort sioc names
#
#==============================================================
#
#   cpu_info.sh <cpu-name>
#
#       <cpu-name> is of the form "cpu-l3b-sp02", for example.
#
#   Suggested usage:
#
#       export cpu="cpu-l3b-sp02"
#       cpu_info.sh $cpu > $IOC_DATA/$cpu/cpu_info.before
#
#       upgrade_cpu.sh $cpu upgrade
#       restart_cpu.sh $cpu
#
#       cpu_info.sh $cpu > $IOC_DATA/$cpu/cpu_info.after
#       diff -u $IOC_DATA/$cpu/cpu_info.before $IOC_DATA/$cpu/cpu_info.after
#

# $IOC_OWNER and $FACILITY can be used appropriately
#
# host           facility    user       cpu
# ============   ========    ======     ====================
# lcls-srv01     lcls        laci       cpu-l3b-sp01 (Garth)
# facet-srv01    facet       flaci
# testfac-srv01  testfac     acctf
# lcls-dev3      dev         laci
#

function usage()
{
    echo "Display IOC-related information for a CPU"
    echo ""
    echo "Usage: ${0} cpu_name"
    echo ""
    echo "    cpu_name     The CPU nodename, e.g., cpu-l3b-sp02"
    echo ""
}

export cpu_name="${1:-unknown}"
export cpu_user="${IOC_OWNER:-unknown}"

export ssh_options="-o StrictHostKeyChecking=no"

if [ "${cpu_user}" == "unknown" ]; then
    echo '${IOC_OWNER} not set appropriately!'
	exit 2;
fi

if [ "${cpu_name}" == "unknown" ]; then
    echo "Unknown cpu name"
    usage;
    exit 1;
fi

echo "# CPU ${cpu_name} info   (`date -R`)"

ssh ${ssh_options} ${IOC_OWNER}@${cpu_name} uname -a

echo "# List all IOC's - based on iocConsole.sh"

export cpu_cmd="cd /home/${IOC_OWNER} ; source /etc/profile >/dev/null 2>&1 ; iocConsole.sh -l | sort"
ssh ${ssh_options} ${IOC_OWNER}@${cpu_name} ${cpu_cmd}

echo "# Running IOC's - based on screen"

export cpu_cmd="screen -ls | sed -e 's/[^.]*\.\(.*\)/\1/' | sort"
ssh ${ssh_options} ${IOC_OWNER}@${cpu_name} "${cpu_cmd}"

echo "# Running IOC's - based on ps"

ssh ${ssh_options} ${IOC_OWNER}@${cpu_name} ps aux | grep SCREEN | sed -e 's/.* -S \(.*\)/\1/'

echo "# ifconfig status"

ssh ${ssh_options} ${IOC_OWNER}@${cpu_name} 'PATH="$PATH:/usr/sbin" ; ifconfig'

echo "# dhcpd status"

result=`ssh ${ssh_options} ${IOC_OWNER}@${cpu_name} ps aux | grep dhcpd`

if [ -n "$result" ]; then
    cpu_cmd="cat /data/${cpu_name}/dhcpd/dhcpd.leases"
    ssh ${ssh_options} ${IOC_OWNER}@${cpu_name} ${cpu_cmd}
else
    echo "  N/A"
fi

echo "# Kernel modules"

ssh ${ssh_options} ${IOC_OWNER}@${cpu_name} 'PATH="$PATH:/usr/sbin" ; lsmod | sort'

