#
# Check the remaining time on user's tokens.
#
# by bert Dvornik <bert@mit.edu>, Watchmaker Zone Night Patrol
#
# $Id: tokens.pl,v 1.2 1996/04/14 13:05:04 bert Exp $

unshift(@RCSID, '$Id: tokens.pl,v 1.2 1996/04/14 13:05:04 bert Exp $');

package tokens;

@month_name = ('Jan','Feb','Mar','Apr','May','Jun',
	       'Jul','Aug','Sep','Oct','Nov','Dec');

sub main'get_token_lifetime {
    local($cellname) = @_;
    local($found, $expired, $lifetime, $lt);
    local($now) = time;
    local($s,$m,$h, $mday,$month) = localtime($now);
    $now -= $s;  # start at the start of minute

    open(TOKENS, "tokens |") || die 'Cannot run "tokens": $@\naborting';

    while (<TOKENS>) {
	if (/\s+tokens\s+for\s+afs@$cellname/i) {
	    $found++;
	    if (/\[\s*Expires\s+(\w+)\s+(\d+)\s+(\d+):(\d+)\s*\]/i) {
		$lt = ($4 - $m) + 60*($3 - $h);
		if ((($1 eq $month_name[$month]) && ($2 > $mday)) ||
		    (($1 ne $month_name[$month]) && ($2 < $mday))) {
		    $lt += 24*60;
		}
		$lifetime = $lt if (!defined($lifetime) || ($lt < $lifetime));
	    } else {
		$expired++;
	    }
	}
    }

    return -1 if (!$found || $expired);

    $expiration{$cellname} = $now + (60*$lifetime);
    $lifetime;
}

$user = $ENV{'USER'} || $ENV{'LOGNAME'};

sub main'token_expiration_alert {
    local($seconds, $xseconds, $cell) = @_;
    local($lifetime);

    if (! $expiration{$cell}) {
	$lifetime = 60 * &main'get_token_lifetime($cell);
    }
    $lifetime = $expiration{$cell} - time;

    if ($lifetime < $seconds) {
	if ($lifetime > 0) {
	    printf STDOUT <<"EndOfFormat",
               *** WARNING ****** WARNING ****** WARNING ***
                  Your tokens will expire in %02dh %02dm %02ds.
    You are advised to renew your tickets and tokens before proceeding.
If you don't, please let everyone know you are about to use strong language.
               *** WARNING ****** WARNING ****** WARNING ***

Press RETURN to continue.
EndOfFormat
		$lifetime/3600, ($lifetime/60)%60, $lifetime%60;
	} else {
	    print STDOUT <<"EndOfText";
               *** WARNING ****** WARNING ****** WARNING ***
      You do not seem to have valid tokens for the specified AFS cell.
Go get some before continuing!  (You may need to obtain new tickets first.)
               *** WARNING ****** WARNING ****** WARNING ***

Press RETURN to continue.
EndOfText
        }
	<STDIN>;
	&main'get_token_lifetime($cell);
	if ((($expiration{$cell} - time) < $xseconds) && $xseconds) {
	    print STDOUT <<"EndOfText";
You aren't listening?
      *** THIS WILL HURT.  YOU HAVE BEEN WARNED.  HAVE A NICE DAY. ***

Press RETURN to continue.
EndOfText
            <STDIN>;
	}
	return ($lifetime);
    }
    ();
}

1;

