#!/bin/sh
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html

# Opens the specified table in the users editor;writes changes back to the db

function cexit {
  if [ -d /tmp/tabedit.$$ ]; then
    rm -rf /tmp/tabedit.$$;
  fi
  exit
}
trap cexit 2 15

if [ -r /etc/profile.d/xcat.sh ]; then
    #Source for environment variables
    source /etc/profile.d/xcat.sh
fi

TABLE=$1

if [ $TABLE = "eventlog" ]  || [ $TABLE = "auditlog" ]; then
    echo "The auditlog and eventlog tables may not be edited. Editing will cause index regeneration.";
    exit 1
fi
if [ -z "$TABEDITOR" ]; then
  TABEDITOR=$EDITOR
fi
if [ -z "$TABEDITOR" ]; then
  #echo "WARNING: Define TABEDITOR or EDITOR environment variable before running this command"
  TABEDITOR=vi
fi
if [ -z "$TABLE" -o "$TABLE" = "-?" -o "$TABLE" = "-h" -o "$TABLE" = "--help" ]; then
    echo "Usage: tabedit <tablename>";
    echo "       tabedit [-? | -h | --help]";
    exit 1
fi

# Dump the table to a temporary file
mkdir -p /tmp/tabedit.$$/
$XCATROOT/bin/xcatclientnnr tabdump $TABLE > /tmp/tabedit.$$/$TABLE.csv

# Save the checksum to see if it actually changes..
if [ `uname` = "AIX" ]; then
	SUMPROGRAM=sum
else
	SUMPROGRAM=md5sum
fi
SUM=`$SUMPROGRAM /tmp/tabedit.$$/$TABLE.csv`

# Edit the file, then check it
EXIT=0
while [ $EXIT -eq 0 ]; do
  cd /tmp/tabedit.$$
  $TABEDITOR $TABLE.csv
  cd - >/dev/null
  NEWSUM=`$SUMPROGRAM /tmp/tabedit.$$/$TABLE.csv`
  if [ "$NEWSUM" == "$SUM" ]; then
    echo "No file modifications detected, not restoring."
    break;
  fi
  if `dirname $0`/tabrestore /tmp/tabedit.$$/$TABLE.csv; then
    break;
  else
    echo "Above errors occured, hit enter to edit, or ctrl-c to abort"
    read JNK
  fi
done
cexit

