#!/bin/sh
#
# Copyright (c) 2005, 2013 University of Utah and the Flux Group.
# 
# {{{EMULAB-LICENSE
# 
# This file is part of the Emulab network testbed software.
# 
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
# 
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
# 
# }}}
#
# Wicked sleezy script for turning write-cache-enable (WCE) on and off
# for a SCSI drive.  It is sleezy because it acts both as the user interface
# and as a back-end editor for camcontrol depending on how it is called.
#
# Why is this needed?  We need to make up for the lack of a batch mode
# style of operation in camcontrol coupled with a desire not to install
# "ed" (rather the 1MB crypto library it depends on but would never use)
# in the MFS just to edit the camcontrol tmp file and change 1 bit.
#
# Note that we are only changing the "current" state so the previous WCE
# state will be restored on a machine reset.
#

if [ -r /etc/emulab/paths.sh ]; then
	. /etc/emulab/paths.sh
else
	BINDIR=/etc/testbed
fi

pgctl="-P0"
prefix=""
if [ $# -gt 0 -a "$1" = "-P" ]; then
    pgctl="-P3"
    prefix="persistent "
    shift
fi

if [ $# -lt 1 ]; then
    echo 'usage: camwce [-P] <on|off> <dev>'
    exit 1
fi
cof=$1
case $cof in
on|off)
    if [ $# -lt 2 ]; then
	echo 'usage: camwce <on|off> <dev>'
	exit 1
    fi
    dev=$2
    case $dev in
    da*)
	;;
    *)
        echo "$dev: not a SCSI device"
        exit 1
	;;
    esac
    wce=`camcontrol modepage $dev -m8 $pgctl | grep 'WCE:' | sed 's/WCE:[ 	]*\([01]\)/\1/'`
    if [ $cof = "on" -a "$wce"x = "0x" -o $cof = "off" -a "$wce"x = "1x" ]
    then
	echo "${dev}: turning ${prefix}write-cache $cof"
	EDITOR=$BINDIR/camwce camcontrol modepage $dev -m8 $pgctl -e
    else
	echo "${dev}: ${prefix}write-cache already $cof"
	exit 1
    fi
    ;;
*)
    #
    # sleezy: when invoked with one arg, we are being called as an
    # editor and need to toggle the WCE bit in the given file using an
    # obscure sed invocation.
    #
    if [ $# -ne 1 ]; then
	echo 'usage: camwce [-P] <on|off> <dev>'
	exit 1
    fi
    sed -i '' -e '/WCE:[ 	]*[01]/y/01/10/' $cof
    ;;
esac
exit $?
