#!/bin/sh
#
# find the default gateway

# Ensure ZEUSHOME is setup to point to our installation
if [ -z "$ZEUSHOME" ]
then
    # Have a good guess, we live in $ZEUSHOME/zxtm/bin
    OLD_PWD=`pwd`
    cd `dirname $0`/../..
    ZEUSHOME=`pwd`
    export ZEUSHOME
    cd $OLD_PWD
fi

if [ ! -d "$ZEUSHOME/zxtm" ]
then
   echo "get-gateway FATAL: ZEUSHOME not set"
   exit 1
fi

# Try to get networking commands into our PATH
PATH=/sbin:/usr/etc/sbin:/usr/etc:/usr/sbin:$PATH

# Restart ourselves in perl
exec $ZEUSHOME/perl/miniperl -x $0 ${1+"$@"}

#!perl -w

# Work out what platform we're running on.
$platform = `uname`;
chomp $platform;
if ($platform ne "Linux"
    && $platform ne "SunOS"
    && $platform ne "FreeBSD"
    && $platform ne "OpenBSD"
    && $platform ne "OSF1"
    && $platform ne "HP-UX"
    && $platform ne "AIX"
    && $platform ne "Darwin"
    && $platform !~ m/^IRIX/) {
    print "FATAL: get-gateway doesn't know about platform $platform yet\n";
    exit 1;
}

my $gw = undef;
# On Linux, try the 'modern' /sbin/ip first as netstat isn't always installed.
# On all other platforms, and on Linux if ip is not available, we use netstat
# as it has the same command form everywhere.
if( $platform eq "Linux" && open( my $ipfd, "/sbin/ip -4 route show default|" ) ) {
   while( my $line = <$ipfd> ) {
      if( $line =~ /default\s+via\s+(\d+\.\d+\.\d+\.\d+)\s+/ ) {
         $gw = $1;
         last;
      }
   }
   close( $ipfd );
}

if( !defined( $gw ) ) {
   if( open( FILE, "netstat -rn |" ) ) {
      while (<FILE>) {
         next if not /^\s*(0\.0\.0\.0|default)/ ;

         /^\s*([0\.]+|default)\s+([0-9\.]+)\s+.*$/;
         $gw = $2;
         last;
      }
      close( FILE );
   } else {
      die "FATAL: netstat failed: $!\n";
   }
}
if( defined( $gw ) ) {
   print( $gw, "\n" );
}
exit(0);
