#!/usr/bin/env perl
# runhtpdate - Simple wrapper for "htpdate".
# License:  BSD-style [for this file only]
# Revision: 080512

#---------------------------------------------------------------------
#                            module setup
#---------------------------------------------------------------------

require 5.6.1;
use strict;
use Carp;
use warnings;
                                # Trap warnings
$SIG {__WARN__} = sub { die @_; };

#---------------------------------------------------------------------
#                           basic constants
#---------------------------------------------------------------------

use constant ZERO  => 0;        # Zero
use constant ONE   => 1;        # One

use constant FALSE => 0;        # Boolean FALSE
use constant TRUE  => 1;        # Boolean TRUE

#---------------------------------------------------------------------
#                            main routine
#---------------------------------------------------------------------

sub Main
{
    my $cmd;
    my $route;
    my $str;

    select STDERR; $| = ONE;
    select STDOUT; $| = ONE;

    $route = `/sbin/route -n 2>&1`;
    $route = "" if !defined $route;

    if ($route !~ m@\n0\.0\.0\.0\s@)
    {
        print STDERR "htpdate: Network seems to be down\n";
        exit ONE;
    }

    print "htpdate: Setting time using HTTP\n";
    $str =  `htpdate -4 -p9 -a -s google.com ibm.com 2>&1`;
    $str =  "" if !defined $str;
    $str =~ s@\s*\z@\n@s;

    if ($str =~ m@Setting -?\d.+second@)
    {
                                # Prepare an appropriate command
        $cmd = '/sbin/hwclock --systohc';

                                # "Log" the command we're about to run
        if (open (OFD, ">>/var/log/hwclock"))
        {
            print OFD "runhtpdate: Running $cmd\n";
            close OFD;
        }
                                # Run the command
        system "$cmd >> /var/log/hwclock 2>&1";
        print "$str\n";
    }
    elsif ($str =~ m@No time correction needed@)
    {
        print "htpdate: No time correction needed\n";
    }
    else
    {
        print STDERR << "END";
htpdate: Operation failed:
$str
END
        exit ONE;
    }

    undef;
}

#---------------------------------------------------------------------
#                            main program
#---------------------------------------------------------------------

&Main();                        # Call the main routine
exit ZERO;                      # Normal exit
