#!/usr/bin/suidperl -w

# Copyright Daniel O'Connor 2003
# darius@dons.net.au
# Public Domain

# This script should be setuid whoever owns the secretfile

# Needs the following Perl packages
# www/p5-libwww
# security/p5-Crypt-SSLeay (for https connects)
# devel/p5-Date-Manip

# Information about the format sent by the web server is available
# from http://slash.dotat.org/~newton/padsl-usage.html

use strict;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use Date::Manip;

# Edit this to point to where your username and password are kept
# Should be a plain file with "username password" on one line.
# Should be chmod 600 for security.

my $secretfile = "/home/doconnor/bin/internode.secret";

my $proxyurl;
# Edit this to point to your proxy if any or comment out
$proxyurl = "http://proxy.gsoft.com.au:3128/";

my $maxpct = 90;

%ENV = (PATH => '/bin');

my($username,$password, $ua, $data, @d, $warn, $max, $sofar);

open(SECRET, $secretfile) || die("can't open secretfile: $!");
while (<SECRET>) {
  if (/(.*) (.*)/) {
    $username = $1;
    $password = $2;
  }
}
close SECRET || die "can't close secretfile: $!";

$ua = LWP::UserAgent->new;
$ua->proxy(['http', 'https', 'ftp'], $proxyurl) if defined($proxyurl);

my $req = POST 'http://accounts.internode.on.net/cgi-bin/padsl-usage',
  [username => $username, password => $password, speed => 0, history => 0, iso => 1];

# Pass request to the user agent and get a response back
my $res = $ua->request($req);

# Check the outcome of the response
die "Query failed -- ", $res->status_line unless $res->is_success;

$data = $res->content;
if ($data =~ "Authentication failed") {
  die "Authentication failed";
}

chomp $data;
@d = split(/ /, $data);
$sofar = $d[0];
$max = $d[1];
die "Unable to parse $data" unless defined($max) && defined($sofar);
$warn = $max * $maxpct / 100.0;

my($datefrom, $dateto, $from, $to, $daysleft, $billbeg, $billbegtm, $daysdone);
$datefrom = &ParseDate("today");
$dateto = &ParseDate("$d[2]");
$billbeg = &DateCalc($dateto, "- 1 month");
$from = &UnixDate($datefrom, "%s");
$to = &UnixDate($dateto, "%s");
$billbegtm = &UnixDate($billbeg, "%s");

$daysleft = ($to - $from) / (24 * 60 * 60);
$daysdone = ($from - $billbegtm) / (24 * 60 * 60);

my($mbperday, $projtot);
$mbperday = $sofar / $daysdone;
$projtot = $daysleft * $mbperday + $sofar;
if ($#ARGV == -1 || $ARGV[0] ne "-s") {
  printf "Usage %.1fMb of %.1fMb (%.1f%%)\n", $sofar, $max, $sofar / $max * 100.0;
  printf "%.1f days into billing period, new billing period starts in %.1f days\n", $daysdone, $daysleft;
  printf "Average per day %.1fMb, projected total %.1fMb\n", $mbperday, $projtot;
}

if ($sofar > $warn) {
  printf "Usage has exceeded %.1f%% (%.1fMb > %.1fMb) with %.1f days remaining\n", $maxpct,
         $sofar, $warn, $daysleft;
}

