#!/bin/sh
#
# Tune IPFilter as necessary for IP transparency on Solaris

# 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 "ipftune: 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 #"
#line 30

if( defined( $ARGV[0] ) && $ARGV[0] =~ /^--help|-h$/ ) {
   print "This script applies the required tuning for IP transparency on Solaris\n"
       . "(if this can be done safely). It is called by the Stingray Traffic Manager\n"
       . "when the first pool starts using transparency.\n";
   exit( 0 );
}

die "This script is for use on Solaris only\n" unless `uname` eq "SunOS\n";

# Enable IPFilter
system "svcadm enable svc:/network/ipfilter:default";

# Check we aren't about to clobber some existing ipnat rules
open( IPNAT, "ipnat -l |" ) or die $!;
while( <IPNAT> ) {
   last if /^List of active sessions:$/;  # Only care about rules
   next if /^List /;
   next if /^rdr lo0 169\.254\.254\.254\/32 -> 169\.254\.254\.254 ip$/;  # We add this
   next unless /./;
   print STDERR "Non-Stingray ipnat rules are present; can't safely apply tuning; see manual\n";
   exit( 1 ) ;
}
close( IPNAT );

# This will wipe any rules/mappings (because it disables ipfilter temporarily)
system "ipf -D -T ipf_nattable_max=2000000,ipf_nattable_sz=2666663,fr_tcptimeout=40,fr_tcpclosed=40 -E";

# Might say "File exists" if we already added it, which is fine
open( IPNATF, "|ipnat -f -" ) or die $!;
print IPNATF "rdr lo0 169.254.254.254 -> 169.254.254.254";
close( IPNATF );

system "ndd -set /dev/tcp tcp_time_wait_interval 20000";

