#!/usr/local/bin/perl
#+##########################################################################
# File:		tklife
# Description:	Check the token expiration
# Author:       C. Bondila (CERN/CN/DCI)
# Contact:      W. Friebel <Wolfgang.Friebel@desy.de>
# Version:      4.0
# Date:         17 May 1995
# Last Change:  Thu Jan 10 09:17:07 2002 by W. Friebel <friebel@ifh.de>
#-##########################################################################

$ENV{"PATH"}='/usr/sue/bin:/usr/afsws/bin';

use Date::Parse;
use Getopt::Std;

&getopts('l:') || die "Usage: tklife [-l <warning time in hh[:mm:ss]>]";

$warn_time=3600;
$warn_time = $1*3600 + $2*60 + $3 if $opt_l =~ /(\d+):?(\d+)?:?(\d+)?/;

#get token value
$token=`tokens`;

# only for users with a valid AFS home directory
$user=getpwuid($<);
# Get our domain name
if ( -r "/etc/resolv.conf" ) {
  open F, "/etc/resolv.conf";
  while (<F>) {
    $domain = $1, last if /^domain\s+([^\s]+)/;
    $domain = $1, last if /^search\s+([^\s]+)/;
  }
} else {
  $domain = 'ifh.de'; # hopefully we never need that
}
exit unless -d "/afs/$domain/user/".substr($user,0,1)."/$user";

if ($token !~ /Expire/) {
   print ">>>>> No AFS token! <<<<<\n";
}
else { 
   for (split(/\n/, $token)) {
      next unless /Expire/;
      if ( /t?T?okens for (.*) \[Expires (.*)\]/ ) {
         $cell=$1;
         $date=$2;
         if ( ($secs = mystr2time($date) - time()) <= $warn_time) {
	    printf ">>>>> AFS token is going to expire in %d minutes on $cell! <<<<<\n", int($secs/60);
         }
      } else {
	 print ">>>>> AFS token expired on $1 ! <<<<<\n"
	       if /t?T?okens for (.*) \[>> Expired <<\]/;
      }
   }
}
sub mystr2time
# this routine is identical to str2time except it prefers the future 
# instead of the past, if the year is not given
{
 my @t = strptime(@_);

 return undef
        unless @t;

 my($ss,$mm,$hh,$day,$month,$year,$zone) = @t;
 my @lt  = localtime(time);

 $hh    ||= 0;
 $mm    ||= 0;
 $ss    ||= 0;

 $month = $lt[4]
        unless(defined $month);

 $day  = $lt[3]
        unless(defined $day);

 $year = ($month < $lt[4]) ? ($lt[5] + 1) : $lt[5]
        unless(defined $year);

 return defined $zone ? timegm($ss,$mm,$hh,$day,$month,$year) - $zone
                      : Date::Parse::timelocal($ss,$mm,$hh,$day,$month,$year);
}
