#! /usr/bin/perl

###
### parse_savedsearches.pl - parses the Splunk 3.x savesearches.conf file
### and outputs the stanzas into a user directory where the stanzas are
### written into a file named after the userid of the stanza to comply
### with Splunk 4.x standards
###  
### By Kirk Waingrow (6/2009)
###
###

# Location of user directory where stanza's will be created
$USERDIR="./users";

# The savedsearches.conf file to process
$SSCONF="./savedsearches.conf";

# Create the user directory for the new savesearches to be created in
if ( ! -d "$USERDIR" ) { `mkdir -p $USERDIR`; }

#
# Open the savesearch file for processing
#
@lines="";
open(IN, "$SSCONF") || print "\nERROR: $SSCONF file not found\n\n";
while (<IN>)
{
  chomp;
  next if /^(\s)*$/;

  # Get the UID for the stanza
  if ( /^userid/ ) { ($d1, $d2, $UID) = split(/ /,$_); }

  # When a new stanza is found
  if ( /\[/ ) 
  { 
    # Output the current stanza to the UID
    if (@lines)
    {
      # When the UID is not found, use UNKNOWN as the UID
      if ( ! $UID ) { $UID="UNKNOWN"; }

      # Output the stanza that is in the array
      foreach $i (@lines)
      { 
        open(OUT, ">> $USERDIR/$UID") || print "\nERROR: $USERDIR/$UID not writeable\n\n";
        print OUT "$i\n";
#        print "$i\n";
      }
      close(OUT);
      @lines=""; $UID="";
    }
  }
  push(@lines, $_); 
}
close(IN);
