#!/bin/sh
#
# Name: add_del_mod.sh configure file operation script.
#
# Version: 1.0.0 05-Dec-2008
# Author : [email protected]
#
# Description:
# add, delete and modify specified record in a
# configure file according to parameters.
#
# Synopsis: add_del_mod FILE [ADD|DEL|MOD] [ROW_NUM] [LINE_CONTENT]
#
# Examples:
# add_del_mod /etc/ipsecmc/userip.conf ADD 1 "olymuser 123456 192.168.135.1"
# add_del_mod /etc/ipsecmc/userip.conf MOD 1 "olymuser 123456 10.0.0.1"
# add_del_mod /etc/ipsecmc/userip.conf DEL 1
#
[ "$#" -lt "3" ] && echo "too few parameters!" && exit 1
FILE="$1"
ACTION="$2"
NROW="$3"
TMPFILE="$FILE-$$"
# check file exist or not.
[ ! -e "$FILE" ] && echo "FILE: [$FILE] not exist!" && exit 1
# check row number is a pure number.
[ `echo $NROW | grep -c '^[0-9]*$'` != 1 ] && echo "ROW_NUM: [$NROW] is not digit!" \
&& exit 1
case "$ACTION" in
"ADD")
[ "$#" != "4" ] && echo "too few parameters for action [ADD]!" && exit 1
if [ "$NROW" == "0" ]; then # append to the end of file.
echo "$4" >> $FILE
else
cat $FILE | grep -v '^$' | sed "${NROW}i $4" > $TMPFILE
mv $TMPFILE $FILE
fi
;;
"MOD")
[ "$#" != "4" ] && echo "too few parameters for action [MOD]!" && exit 1
cat $FILE | grep -v '^$' | sed "${NROW}c $4" > $TMPFILE
mv $TMPFILE $FILE
;;
"DEL")
cat $FILE | grep -v '^$' | sed "${NROW}d" > $TMPFILE
mv $TMPFILE $FILE
;;
*)
echo "action [$ACTION] invalid!"
exit 1
;;
esac
exit 0