#!/usr/local/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 <insert names>, 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.2, 8/30/08";
#my $in_fn="/afs/slac/www/grp/scs/net/racks/bldg-switches.csv";
my $in_fn="/afs/slac/www/grp/scs/net/racks/bldg-switches.txt";
my $out_dir="/afs/slac/www/grp/scs/net/racks/slaconly/switches";
#  ....................................................................
(my $progname = $0) =~ s'^.*/'';#strip path components, if any

my $USAGE = "Usage:\t $progname [opts] 
        Opts:
        -v print this USAGE information
        -D debug_level (default=$debug)
        -i input filen of list of switches (default = $in_fn)
        -o output directory (default=$out_dir)
Purpose:
 Using the input file with a list of switch names (one per line), executes 
 an SQL command to provide a tab separated value (.tsv) table of the 
 hosts on the switch together with their IP address, VLAN, MAC address,
 tap, last seen date, user, OU admin, building, room, port.
 The tsv files are saved in the output directory. 
Input file format:
 <switch-name>[,]
 e.g.
 swh-ae1
 swh-ae2

Examples:
 $progname

Version=$version
";

#  Please send comments and/or suggestion to Les Cottrell.
#
# **************************************************************** 
# Owner(s): Les Cottrell (8/30/08).                                
# Revision History:                                                
# **************************************************************** 
#Get some useful variables for general use in code
umask(0002);
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 Sys::Hostname; 
my $ipaddr=gethostbyname(hostname());
my ($a, $b, $c, $d)=unpack('C4',$ipaddr);
my ($hostname,$aliases, $addrtype, $length, @addrs)=gethostbyaddr($ipaddr,2);
my $righthost="net-desk1.slac.stanford.edu";
if($hostname ne $righthost) {
  die "$0 must run on $righthost, you are on $hostname\n";
}

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

if($opt_v) {
  print "$USAGE"; 
  exit 1;
}
if($opt_i) {$in_fn=$opt_i;}
if($opt_d) {$out_dir=$opt_d;}
if($opt_D)  {$debug=$opt_D;}

my $time=localtime();
my $t0=time();
print "$progname: $time=$t0, debug=$debug, input file=$in_fn, output directory=$out_dir\n";
open(STDERR, '>&STDOUT');# Redirect stderr onto stdout
open(IN,"<$in_fn") or die "Can't open $in_fn: $!"; 
unless(-e $out_dir) {
  if(! mkdir($out_dir, '0777')) {die "Can't mkdir $out_dir: $1";}
}
my @switches=<IN>;
my $nswitch=0;
foreach my $line (sort @switches) {
  chomp $line;
  my ($switch,undef)=split(',',$line);
  $switch=~s/\s+//g;
  if($switch eq "") {next;}
  $nswitch++;
  my $sql="select administrator, hostname, ip_address, vlan, mac_address, user, device_type, building, room, alias as tap, physical_port as port, last_seen from admins_on_node where node='$switch.slac.stanford.edu' AND hostname NOT regexp '^dhcp' order by administrator;";
  my @tokens=split(/\./,$progname);
  my $script=$tokens[0]."-temp.sql";
  `rm -f $script`;
  open(OUT,">$script") or die "Can't open $script: $!";
  print OUT $sql;
  close OUT;
  my $cmd="mysql < $script";
  my @ans=`$cmd`;
  my $fn="$out_dir/$switch.tsv";
  open(OUT,">$fn") or die "Can't open $fn: $!";
  print OUT "#Written by $0 using mysql for $user on $hostname at "
      . scalar(localtime())."\n"
      . "#$cmd; where $script contains:\n"
      . "#$sql\n";
  foreach my $key (@ans) {
    if($key eq "") {next;}
    print OUT $key;
  }
  close OUT;
  if($debug>=0) {print "Wrote ".scalar(@ans)." lines to ($nswitch)$fn\n";}
  $cmd="/afs/slac/u/sf/cottrell/bin/switch-needs.pl";
  unless(-x $cmd) {print "Unable to execute $cmd\n";}
  else {
    @ans=`$cmd < $fn > $out_dir/$switch-needs`;
    if($debug>=0) {print "Used $cmd to write $out_dir/$switch-needs\n";}
  }
}
exit 0;
__END__

