#!/usr/bin/env bash
# gw-core-console -- attach to ttyS0 of UK-GW

# Use IP address in case DNS is broken (which it will be,
# because gw-core is also the primary DNS resolver).
bmc_host=bmc-gw.utenos-kolegija.lt
bmc_addr=10.254.28.9

# VLAN for direct L2 access (2023-07-03: likely not needed
# anymore, as the gateway is now gw-b56 rather than gw-core)
phy_dev=eno1
vlan_id=28
vlan_dev=$phy_dev.$vlan_id
vlan_addr=10.254.28.219/24

can_have_vlan() {
	[[ $HOSTNAME == @(ember) ]]
}

do:() {
	(PS4="+ "; set -x; "$@")
}

attach_console() {
	do: rconsole ${bmc_host}@${bmc_addr}
}

has_vlan() {
	ip -j -d link | jq -e -r \
		".[]
		| select(.linkinfo.info_kind == \"vlan\")
		| select(.linkinfo.info_data.id == $vlan_id)
		| .ifname" > /dev/null
}

setup_vlan() {
	if has_vlan; then
		echo "[40;97mVLAN $vlan_id already exists[m"
		vlan_added=0
	else
		echo "[40;97mAdding temporary VLAN interface '$vlan_dev'[m"
		sudo ip link add $vlan_dev link $phy_dev type vlan id $vlan_id &&
		sudo ip link set $vlan_dev alias "Temporary VLAN for ${0##*/}" &&
		sudo ip link set $vlan_dev up &&
		sudo ip addr add $vlan_addr dev $vlan_dev &&
		vlan_added=1
	fi
}

teardown_vlan() {
	if (( vlan_added )); then
		echo "[40;97mRemoving temporary VLAN interface '$vlan_dev'[m"
		sudo ip link del $vlan_dev
		vlan_added=0
	fi
}

usage() {
	echo "Usage: ${0##*/} [-f] [-v]"
	echo ""
	echo "Attach IPMI SOL console to $bmc_addr"
	echo ""
	echo "  -f    Force indirect (routed) access through network"
	echo "  -v    Force direct access through VLAN $vlan_id"
	echo ""
	if can_have_vlan; then
		echo "This host has direct emergency access to BMC VLAN."
	else
		echo "This host does not have direct access to BMC VLAN."
	fi
}

if [[ $1 == --help ]]; then
	usage
elif [[ $1 == -f ]]; then
	echo "[40;93mUsing indirect access through network[m"
	attach_console
elif [[ $1 == -v ]] || can_have_vlan; then
	echo "[40;92mUsing direct access through VLAN $vlan_id[m"
	trap teardown_vlan SIGINT
	setup_vlan
	attach_console
	teardown_vlan
else
	echo "[40;91mNo access from this system, but trying network anyway[m"
	attach_console
fi
