| 
#!/bin/rc
# P - send command to remote power switch (APC AOS 3.7.x)
# requires auth/userpasswd (cf. /sys/src/cmd/auth/userpasswd.c)
rfork en
fn usage {
	echo >[1=2] usage: P system [command]
	exit usage
}
if(~ $#* 0)
	usage
if(~ $#* 1)
	cmd=3
if not
	switch($2){
	case on
		# 1- Immediate On
		cmd=1
	case off
		# 2- Immediate Off
		cmd=2
	case reboot
		# 3- Immediate Reboot
		cmd=3
	case *
		usage
	}
outlet=`{ndb/query sys $1 outlet}
if(~ $outlet ''){
	echo >[1=2] P: unknown outlet for $1
	exit nooutlet
}
power=`{ndb/query sys $1 power}
if(~ $power ''){
	echo >[1=2] P: unknown power for $1
	exit nopower
}
if(! test -e /mnt/consoles/$power){
	server=`{ndb/query sys $power console}
	if(~ $server ''){
		echo >[1=2] P: unknown console server for $power
		exit noserver
	}
	switch($sysname){
	case $server
		mount /srv/consoles /mnt/consoles
	case *
		import $server /mnt/consoles
	}
}
auth=`{auth/userpasswd 'service=power power='$power}
# Unfortunately, AOS 3.7.x is menu-driven, though it is fairly
# forgiving.  We fire and forget a series of commands to a given
# outlet.  Use of an interrupt will always warp us to the topmost
# menu; menus will ignore an authentication attempt if it is
# unnecessary.
{
	# Clear prompt
	echo; echo
	# User Name :
	echo $auth(1)
	# Password :
	echo $auth(2)
	# Send interrupt
	tt '^C'
	# 1- Device Manager
	echo 1
	# 2- Outlet Management
	echo 2
	# 1- Outlet Control/Configuration
	echo 1
	# Select outlet
	echo $outlet
	# 1- Control Outlet
	echo 1
	# Issue command; ignore result
	echo $cmd; echo YES; echo
}>/mnt/consoles/$power
 |