#!/usr/bin/perl -w
# -*- perl -*-


use strict;
package CHIRPList;


use File::Path;
use Getopt::Std;

### Site Specific ###

#Specifies the root of the cricket config tree to place new devices
my($ROOT_DIR)= "/home/cricket/cricket-config";
my($CHIRP) = "./chirp.pl";
my($COMPILE) = "/home/cricket/cricket/compile";

#####################

my($options_ref) = {};

getopts('Hf:i:q', $options_ref);
if($options_ref->{H} || !$options_ref->{f} || $#ARGV != -1) {
	print STDERR "Usage: $0 [-H] -f filename [-i file] [-q]\n",
		"\t-H: This page\n",
		"\t-f: Filename for Devices\n",
		"\t\tFormat of file is:\n",
		"\t\tSUBTREE:DEVICE_NAME:HOSTNAME:SNMP_COMMUNITY:SNMP_PORT:SITE_FILE:COMMENT\n",
		"\t-i: ID config file \n",
		"\t-q: quiet mode\n";
	if (!$options_ref->{H}) {
                exit 1;
        }
        exit 0;
}

my($devicefile);
my($idfile);
my($quiet) = 0;

if(defined($options_ref->{f})) {
	$devicefile = $options_ref->{f};
}
if(defined($options_ref->{i})) {
	$idfile = $options_ref->{i};
}
if(defined($options_ref->{q})) {
	$quiet = 1;
}

my($linenumber) = 0;

open(CONFIGFILE, "< $devicefile") || (print STDERR "ERROR: Unable to open $devicefile\n");

while(<CONFIGFILE>) {
	$linenumber++;

	chomp;

	if ($_ =~ /#.*/){
		# Ignore Commented Line
		next;
	}
	if ($_ =~ /^$/){
		# Ignore Blank Line
		next;
	}

	my($SUBTREE, $DEVICE, $HOSTNAME, $COMMUNITY, $SNMP_PORT, $SITE_FILE, $COMMENT) = split(/:/, $_, 7);

	if(!defined($SUBTREE) || $SUBTREE =~ /^\s*$/) {
		print STDERR "WARNING: $devicefile: $linenumber: Invalid subtree\n";
		next;
	}
	if(!defined($DEVICE) || $DEVICE =~ /^\s*$/) {
		print STDERR "WARNING: $devicefile: $linenumber: Invalid device name\n";
		next;
	}
	if(!defined($HOSTNAME) || $HOSTNAME =~ /^\s*$/) {
		print STDERR "WARNING: $devicefile: $linenumber: Invalid hostname\n";
		next;
	}

	if(!$quiet) {
		print "Creating $ROOT_DIR/$SUBTREE/$DEVICE/Targets\n";
	}

	my($CallCommand) = $CHIRP . " -h $HOSTNAME";

	if(defined($COMMUNITY) && $COMMUNITY !~ /^$/) {
		$CallCommand .= " -c $COMMUNITY";
	}
	if(defined($SNMP_PORT) && $SNMP_PORT !~ /^$/) {
		$CallCommand .= " -p $SNMP_PORT";
	}
	if(defined($SITE_FILE) && $SITE_FILE !~ /^$/) {
		$CallCommand .= " -s $SITE_FILE";
	}
	if(defined($idfile) && $idfile !~ /^$/) {
		$CallCommand .= " -i $idfile";
	}

	my($TARGET_DIR) = $ROOT_DIR . "/" . $SUBTREE . "/" . $DEVICE;
	File::Path::mkpath($TARGET_DIR, 0, 0775);

	$CallCommand .= " > $TARGET_DIR/Targets";

	system($CallCommand);
}

close(CONFIGFILE);

system($COMPILE);

exit 0;
