#!/bin/bash
# ---------------------------------------------------------------------------
# NAME
#
#     ReadPowerSwitch - reads the state of one of the configurable power
#                      switches
#
# SYNOPSIS
#
#     sudo ReadPowerSwitch switch-number
#
# DESCRIPTION
#
#     The SMC has four (4) power switches that can be controlled through
#     software.  This script reads the state of any one switch.
#
#         switch-number is a number 1..4
#
# ---------------------------------------------------------------------------

# exit if not run as root
CURUSER=`whoami`

if [ "$CURUSER" != "root" ]
then
	echo "This script must be run as root "
	exit 1
fi

# alias parameters and check ranges
base=`basename $0`
switch_num="$1"

if [ -z "$switch_num" ]
then
	echo "switch number not specified; listing 1 - 4"
	### exit 1
        let begin=1
        let end=4
else
	let begin=$switch_num
	let end=$switch_num

	if [ "$switch_num" -lt 1 ]
	then
		echo "$base: switch number ($switch_num) must be in the range 1..4"
		exit 1
	fi

	if [ "$switch_num" -gt 4 ]
	then
		echo "$base: switch number ($switch_num) must be in the range 1..4"
		exit 1
	fi
fi

# using a file lock prevents contention over the I2C bus
(
flock -x 200

# read the state of the port
status0=`i2cget -y 2 0x3C 0x00`
switch_mask=$(($status0))
let sw=$begin
while [ $sw -le $end ]; do
	let "s=$sw-1"
	let "n=1<<$s"
	let "switch_state=$n & $switch_mask"
	if [ "$switch_state" -gt  "0" ]; then
  		echo ON
	else
  		echo OFF
	fi
	let sw=$sw+1
done

exit 0

) 200>`which SetPowerSwitch`.lockfile
