#!/usr/bin/perl
#
# setfield.pl - Update field value in a syssumm info-file
# 
# Synopsis:
# 
#	setfield.pl category:sub-category:value profile [ profile ... ]
# 
# ==============================================================
# 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; either version 
# 2 of the License, or (at your option) any later version.
# 
# 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.
# 
# Original source:
# 	Copyright (c) 1999, 2000 Martin Andrews (mandrews@netgenics.com)
# 
# Contributed source:
# 	Copyright (c) 1999, 2000 <author>
# 
# ==============================================================
# 
# $Header: /export/home/mohlerb/src/perl/syssumm/web.server/RCS/setfield.pl,v 1.2 1999/08/06 21:54:49 mohlerb Exp mohlerb $
# 
# $Revision: 1.2 $
# 
# $Log: setfield.pl,v $
# Revision 1.2  1999/08/06 21:54:49  mohlerb
# changes from Paul Farrall including:
# changed default path to Perl to /usr/bin
#
# Revision 1.1  1999/07/02 16:44:02  mohlerb
# Initial revision
#

$usage = "$0: category:sub-category:value info-file ...\n";

if ( @ARGV < 2 ) {
    print "$0: too few arguments\n\n$usage";
    exit(1);
}

# Grab new field definition from command line (format is same as
# a line from an info file).

($category, $item, $value) = split (":", shift(@ARGV));
$match = "$category:$item";
$match_len = length($match);

# Each remaining argument if a syssumm file (or directory containing a
# "syssumm.info" file) to update - iterate over them.

foreach $file ( @ARGV ) {
    if ( $file !~ /syssumm.info$/ ) {
	# File not named "syssum.info" - assume it is a directory.

	$file = $file . "/syssumm.info";
    }

    # Move the file to a backup location.

    $bak = "$file.bak";
    rename($file, $bak) or die "can't backup $file: $!";

    # Now copy backup to orignal location, replacing the requested field.

    open OLDFILE, "<$bak" or die "can't open $bak for reading: $!";
    open NEWFILE, ">$file" or die "can't open $file for writing: $!";
    while ( $line = <OLDFILE> ) {
	if ( substr($line, 0, $match_len) eq $match ) {
	    # This is the field to update.

	    print NEWFILE "$category:$item:$value\n"
	} else {
	    # No change to this field.

	    print NEWFILE $line;
	}
    }
    close OLDFILE;
    close NEWFILE;
}
