#!/bin/sh

debug=$1
dist="conf/scipfire.cfg.dist"
conf="conf/scipfire.cfg"

DEF_INT=`netstat -rn | grep "^0.0.0.0" | awk '{print $8}'`

NUMINT=`ifconfig | grep -v "^ " | awk '{print $1}' | grep eth[0-9]* | wc -l | sed 's/ //g'`
if [ "x$NUMINT" = "x2" ]; then
  for INT in `ifconfig | grep -v "^ " | awk '{print $1}' | grep eth[0-9]*`; do
    IP=`ifconfig $INT | grep inet | awk '{print $2}' | sed 's/^.*://'`
    BROADCAST=`ifconfig eth0 | grep inet | awk '{print $3}' | sed 's/^.*://'`
    MASK=`ifconfig eth0 | grep inet | awk '{print $4}' | sed 's/^.*://'` 
    NET=`bin/ipcalc.pl -n $IP/$MASK | grep Network | awk '{print $2}'` 
    if [ "x$debug" != "x" ]; then
      echo "$INT: $IP/$MASK broadcast $BROADCAST in $NET"
    fi
    if [ "x$IP" = "x" ]; then
      echo "Interface $INT has no ip address configured. Skipping."
      exit
    fi
    if [ "x$INT" = "x$DEF_INT" ]; then
      IN_NET="$NET"
      IN_BROADCAST="$BROADCAST"
      IN_ME="$IP"
      IN_INT="$INT"
    else
      EX_NET="$NET"
      EX_BROADCAST="$BROADCAST"
      EX_ME="$IP"
      EX_INT="$INT"
    fi
  done
else
  echo "You have $NUMINT interfaces. $0 requires 2 interfaces for"
  echo "automatically setting up your scipfire configuration."
  echo "Please configure your firewall manually. Sorry 'bout that."
  exit
fi

if [ "x$IN_NET" = "x" ]; then
  echo "Could not determine which interface is the internal network."
  echo "Maybe you are using a dialup account. In this case configure"
  echo "scipfire manually. Sorry 'bout that."
  exit
fi

iptables=`which iptables`

echo "Configuring scipfire with the following values:
IN_NET:       $IN_NET
IN_BROADCAST: $IN_BROADCAST
IN_ME:        $IN_ME
IN_INT:       $IN_INT

EX_NET:       $EX_NET
EX_BROADCAST: $EX_BROADCAST
EX_ME:        $EX_ME
EX_INT:       $EX_INT

iptables:     $iptables
"

	
cmd="cat $dist |
sed 's/iptables=/iptables=\"$iptables\"/' |
sed 's/IN_NET=/IN_NET=\"$IN_NET\"/' |
sed 's/IN_BROADCAST=/IN_BROADCAST=\"$IN_BROADCAST\"/' |
sed 's/IN_ME=/IN_ME=\"$IN_ME\"/' |
sed 's/IN_INT=/IN_INT=\"$IN_INT\"/' |
sed 's/EX_NET=/EX_NET=\"$EX_NET\"/' |
sed 's/EX_BROADCAST=/EX_BROADCAST=\"$EX_BROADCAST\"/' |
sed 's/EX_ME=/EX_ME=\"$EX_ME\"/' |
sed 's/EX_INT=/EX_INT=\"$EX_INT\"/' > $conf"

echo "Writing config to $conf"
eval $cmd


echo "done. Now run "\make install\"."
