#!/bin/sh
# Copyright (c) 2003 International Business Machines
# Common Public License Version 0.5 (see COPYRIGHT)

# Simple script to update flash.  The kernel module rtas_flash does
# the real work at reboot time.
# This script has minimal dependencies so it can operate in a rescue
# environment.  This is probably overkill since it is easy enough to
# flash without this script.

PATH=/sbin:/usr/sbin:/bin:/usr/bin:$PATH
procflash=/proc/ppc64/rtas/firmware_flash

function error {
	echo update_flash: $* >&2
	exit 1
}

function usage {
	echo "USAGE:  update_flash [-q] -f file.img" >&2
	exit 1
}

[ -d /proc/device-tree ] || error "iSeries or /proc not mounted"

[ "`whoami`" = "root" ] || error "must be root to execute this command"

file=""
while [ -n "$1" ]; do
	arg="$1"
	shift
	case "$arg" in
	  -q|-D) error "the $arg option is not implemented";;
	  -f) file="$1"; shift;;
	  *) error "unknown option $arg"
	esac
done

[ -n "$file" ] || usage

[ -r "$file" ] || error "cannot read $file"

modprobe rtas_flash || error "could not load rtas_flash kernel module"

[ -r "$procflash" ] || error "rtas_flash kernel module did not create $procflash"

# ToDo: perform a test on the flash file to ensure it is likely it is a
# valid file.  For example, if it is compressed complain (or decompress it).

cp "$file" "$procflash" || error "error copying flash image to rtas_flash kernel module"

if grep -q ready: "$procflash"; then
	echo "Flash image ready...rebooting the system..."
	shutdown -r now
	exit 0
else
	# The proc file contains the error message.
	# Most likely there is no service authority.
	cat "$procflash" >&2
	exit 1
fi
