#!/bin/sh
# arkmigrate_journal: Arkeia Journal Migration Script
# This script is intended to migrate the old v4.2, v5.0 and v5.1 logs
# to the new v5.2 format.
# Copyright Arkeia Corporation 2004

VERSION="5.3.10"
ARKEIA_DIR=`cat /etc/opt/arkeia/ARKEIA_DIR`
MV="mv -f"
RM="rm -f"
ECHO="echo"


new_arkdir=''
nobackup=''


usage() {
	$ECHO "Arkeia Journal Migration Script Version $VERSION"
	$ECHO "Usage:"
	$ECHO "  arkmigrate_journal [options]"
	$ECHO "    options:"
	$ECHO "       -h: prints this usage message"
	$ECHO "       -f: the default is to migrate all the "$ARKEIA_DIR"/server/*.jl2"
	$ECHO "           files to the v5.2 journal format and to backup the old journals in"
	$ECHO "           .bak files. With the -f option, no backup is performed."
	$ECHO "       -d path: by default the migration is performed on the Arkeia installation"
	$ECHO "          given by the file /etc/opt/arkeia/ARKEIA_DIR. You can specify an"
	$ECHO "          alternate Arkeia path with the -d option."
	$ECHO ""
	$ECHO "CAUTION: please before proceeding the migration, make a tar backup copy of"
	$ECHO "the "$ARKEIA_DIR"/server/*.jl2 files because this program will change them."
	$ECHO ""
	exit 0
}

check_error() {
	lasterr=$?
	if [ $lasterr != 0 ] ; then
		$ECHO "Bad end"
		exit $lasterr
	fi
}

while [ ${#} -ge 1 ] ; do
	case $1 in
		-h)
			usage
			;;
		-f)
			nobackup="1"
			;;
		-d)
			shift
			if [ ${#} -eq 0 ] ; then
				$ECHO "Parameter missing for -d option"
				exit 1
			fi
			new_arkdir=$1
			;;
		*)
			$ECHO "unknown option $1"
			usage
			;;
	esac
	shift
done

if [ -z "$new_arkdir" ] ; then new_arkdir="$ARKEIA_DIR" ; fi

if [ ! -d "$new_arkdir/server" ] ; then $ECHO "$new_arkdir: no such directory!"; exit 1; fi

$ECHO "Migrating $new_arkdir/server/*.jl2 logs."

cd "$new_arkdir"/server

for str in `ls *.jl2`; do
	$ECHO "    Migrating $str..."
	$MV "$str" "$str".bak
	check_error
	sed -e 's/^\([^A][^WIE][^WIE]*\)\([WEI]\)\(001.....\) \(.\)\(.*\)/A \1\200000000 D\5/g' -e 's/^\([^A][^WIE][^WIE]*\)\([WEI]\)\(006.....\) \(.\)\(.*\)/A \1\200000000 R\5/g' -e 's/^\([^A][^WIE][^WIE]*\)\([WEI]\)\(009.....\) \(.\)\(.*\)/A \1\200000000 T\5/g' -e 's/^\([^A][^WIE][^WIE]*\)\([WEI]\)\(........\)\(.*\)/A \1\200000000\4/g' "$str".bak > "$str"
	check_error
	if [ ! -z "$nobackup" ] ; then
		$RM "$str".bak
		check_error
	fi
done

$ECHO "Migration OK. "
