#!/bin/sh
#
#  Copyright (C) 2008 Sony Computer Entertainment Inc.
#  Copyright 2008 Sony Corp.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; version 2 of the License.
#
#  This program 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 General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

usage() {
	echo -n "
SYNOPSIS
     ps3-bl-option [OPTION]
DESCRIPTION
     Get and set PS3 bootloader options in flash.
OPTIONS
     -m, --get-video-mode
             Get the bootloader video mode.
     -M, --set-video-mode value
             Set the bootloader video mode.
     -o, --get-bootloader-timeout
             Get the bootloader timeout in seconds.
     -O, --set-bootloader-timeout value
             Set the bootloader timeout in seconds.
     -p, --get-bootloader-default
             Get the default bootloader menu item.
     -P, --set-bootloader-default value
             Set the default bootloader menu item.
     -t, --get-telnet-enabled
             Get the telnet enabled flag.
     -T, --set-telnet-enabled value
             Set the telnet enabled flag.
     -h, --help
             Print a help message.
SEE ALSO
     ps3-flash-util(8)
"
}

bad_arg() {
	echo "ERROR: bad arg" >&2;
	usage
	exit 1
}

if [ "$#" -eq 0 ] ; then
	bad_arg
fi

get_flag() {
	flags=`ps3-flash-util --db-print $1 $2`
	echo $(( ${flags:-0} & $3 ))
}

set_flag() {
	flags=`ps3-flash-util --db-print $1 $2`

	if [ $4 -eq 0  ]; then
		ps3-flash-util --db-write-half $1 $2 $(( ${flags:-0} & ~$3 ))
	else
		ps3-flash-util --db-write-half $1 $2 $(( ${flags:-0} | $3 ))
	fi
}

# owners
bootloader="3"

# keys
item="1"
video="2"
flags="3"
timeout="4"

# flags
telnet="1"

case "$1" in
	-m | --get-video-mode)
		ps3-flash-util --db-print ${bootloader} ${video}
		;;
	-M | --set-video-mode)
		ps3-flash-util --db-write-half ${bootloader} ${video} $2
		;;
	-o | --get-bootloader-timeout)
		ps3-flash-util --db-print ${bootloader} ${timeout}
		;;
	-O | --set-bootloader-timeout)
		ps3-flash-util --db-write-half ${bootloader} ${timeout} $2
		;;
	-p | --get-bootloader-default)
		ps3-flash-util --db-print ${bootloader} ${item}
		;;
	-P | --set-bootloader-default)
		ps3-flash-util --db-write-word ${bootloader} ${item} $2
		;;
	-t | --get-telnet-enabled)
		get_flag ${bootloader} ${flags} ${telnet}
		;;
	-T | --set-telnet-enabled)
		set_flag ${bootloader} ${flags} ${telnet} $2
		;;
	-h | --help)
		usage
		exit 0
		;;
	*)
		bad_arg
		;;
esac