#!/usr/bin/perl -w
#See https://confluence.slac.stanford.edu/display/IEPM/IEPM+Perl+Coding+Styles
#for version of perl to use.

# /*---------------------------------------------------------------*/
# /*          STANFORD UNIVERSITY NOTICES FOR SLAC SOFTWARE        */
# /*               ON WHICH COPYRIGHT IS DISCLAIMED                */
# /*                                                               */
# /* AUTHORSHIP                                                    */
# /* This software was created by Fahad Satti, Stanford Linear     */
# /* Accelerator Center, Stanford University.                      */
# /*                                                               */
# /* ACKNOWLEDGEMENT OF SPONSORSHIP                                */
# /* This software was produced by the Stanford Linear Accelerator */
# /* Center, Stanford University, under Contract DE-AC03-76SFO0515 */
# /* with the Department of Energy.                                */
# /*                                                               */
# /* GOVERNMENT DISCLAIMER OF LIABILITY                            */
# /* Neither the United States nor the United States Department of */
# /* Energy, nor any of their employees, makes any warranty,       */
# /* express or implied, or assumes any legal liability or         */
# /* responsibility for the accuracy, completeness, or usefulness  */
# /* of any data, apparatus, product, or process disclosed, or     */
# /* represents that its use would not infringe privately owned    */
# /* rights.                                                       */
# /*                                                               */
# /* STANFORD DISCLAIMER OF LIABILITY                              */
# /* Stanford University makes no representations or warranties,   */
# /* express or implied, nor assumes any liability for the use of  */
# /* this software.                                                */
# /*                                                               */
# /* STANFORD DISCLAIMER OF COPYRIGHT                              */
# /* Stanford University, owner of the copyright, hereby disclaims */
# /* its copyright and all other rights in this software.  Hence,  */
# /* anyone may freely use it for any purpose without restriction. */
# /*                                                               */
# /* MAINTENANCE OF NOTICES                                        */
# /* In the interest of clarity regarding the origin and status of */
# /* this SLAC software, this and all the preceding Stanford       */
# /* University notices are to remain affixed to any copy or       */
# /* derivative of this software made or distributed by the        */
# /* recipient and are to be affixed to any copy of software made  */
# /* or distributed by the recipient that contains a copy or       */
# /* derivative of this software.                                  */
# /*                                                               */
# /* SLAC Software Notices, Set 4 (OTT.002a, 2004 FEB 03)          */
# /*---------------------------------------------------------------*/
# Copyright (c) 2006, 2007    
# The Board of Trustees of          
# the Leland Stanford Junior University. All Rights Reserved.       

#The following code is placed at the top to ensure we are able to use perl -d
#and stop things before they call other things.
my $debug; #For cronjobs use -1, for normal execution from command line use 0, 
           #for debugging information use > 0, max value = 3.
if (-t STDOUT) {$debug=0;}
else           {$debug=-1;} #script executed from cronjob

use strict;
my $version="0.1, 5/21/09";
#my $DefaultDir="/usr/local/share/pinger/data";
my $DefaultDir="/home/pingER/share/pinger/data";
#  ....................................................................
(my $progname = $0) =~ s'^.*/'';#strip path components, if any

my $USAGE = "Function:\t This script is used to delete PingER data files
that contain results for more than two months back in time.
The idea is to run this script using a cronjob once a month.

Usage:\t $progname [opts] 
        Opts:
        -v print this USAGE information
        -D debug_level (default=$debug)
        -d dirname (default=$DefaultDir)
Examples:
 $progname
 $progname -v -D 1

Version=$version
";

#  Please send comments and/or suggestion to Les Cottrell.
#
# **************************************************************** 
# Owner(s): Les Cottrell (7/13/04).                                
# Revision History:                                                
# **************************************************************** 
#Get some useful variables for general use in code
umask(0002);
#use Sys::Hostname; 
#my $ipaddr=gethostbyname(hostname());
#my ($a, $b, $c, $d)=unpack('C4',$ipaddr);
#my ($hostname,$aliases, $addrtype, $length, @addrs)=gethostbyaddr($ipaddr,2);
##use Date::Calc qw(Add_Delta_Days Delta_Days Delta_DHMS);
#use Date::Manip qw(ParseDate UnixDate);
use Time::Local;
#my $user=scalar(getpwuid($<));

#use Net::DNS::RR;

##############################################################
#Process options
require "getopts.pl";
our ($opt_d, $opt_c, $opt_v, $opt_D)=("", "", "", "");
&Getopts('d:c:D:v');

if($opt_v) {
  print "$USAGE"; 
  exit 1;
}
if(!$opt_d) {$opt_d=$DefaultDir;}
if($opt_D)  {$debug=$opt_D;}

my $time=localtime();
my $t0=time();
if($debug==0)
{
print "$progname: $time=$t0\n";
}
open(STDERR, '>&STDOUT');# Redirect stderr onto stdout
if($debug==0)
{
print "Searching $opt_d for compatible files\n";
}
opendir(DIRHANDLE,$opt_d)|| die "Can;t open Directory: $!";

my @files=grep {-f } map {"$opt_d/$_"} readdir DIRHANDLE;



closedir DIRHANDLE;

my $num=scalar @files;
if($debug==0)
{
print $num.' file'.($num!=1?'s':'') . " found\n";
}
	my $file='';
my ($mon,$yr)=(localtime)[4,5];

my $delMonth=$mon-1;

if($delMonth<0)
{
	$delMonth=$delMonth-11;
	$yr=$yr-1;
}
$delMonth=$delMonth+1;
my $delYear=$yr+1900;

#print $delYear."-".$delMonth."\n";
my $filesDelCount=0;
	foreach $file (@files)
	{
	if($debug==0)
	{
	print $file."\n";
	}
		if($file =~ m/ping\-[1-2][0-9][0-9][0-9]\-[0-1][0-9]/i)
		{
			#print " format ok \n";
			my @fileattr = split('-',$file);
			$fileattr[2]=~ s/\.txt$//i;
			if($fileattr[1] < $delYear)
			{	
				unlink($file);
				$filesDelCount=$filesDelCount+1;
				next;
			}
			elsif($fileattr[2]<=$delMonth)
			{
				unlink($file);
				$filesDelCount=$filesDelCount+1;
				next;
			}
			else
			{
				#print "The file is fine\n";
				next;
			}
		}
		else
		{
			#print " format not ok\n";
		}
	}
if($debug==0)
{
print "$filesDelCount file".($filesDelCount!=1?'s':''). " deleted\n";
}

__END__
