#! /bin/bash

bindir=$( dirname $0 )

function start() {

  # Read the options file:
  local ofile=/etc/default/fw
  if test -r $ofile ; then
    . $ofile
  else
    1>&2 echo "??? No config file '$ofile' ???"
  fi

  if test -n "$gw64" ; then	## we are a 6to4 gateway
    1>&2 echo "Bogus 6to4 vetoed"
    gw64=''
  fi

  if test -n "$gw64" ; then	## we are a 6to4 gateway
    ### 1>&2 echo "we are a gw"
    $bindir/6to4 $info_mode || 1>&2 echo "6to4 returns '$?'"

    if test -n "$info_mode" ; then echo "  .... vassals:"; fi
    set -- $( $bindir/ifc-prop -p private )
    if test -z "$1" ; then
      1>&2 echo "No private-side interfaces???"
      1>&2 echo "Cannot support any vassals."
    fi
##
## Why is this $1 as opposed to $* ?
    for ifc in $1 ; do
      ##1>&2 echo "Configuring IFACE=$ifc"
      IFACE=$ifc $bindir/conf-6-gw $info_mode
    done

    if test -n "$info_mode" ; then echo "  .... ns:"; fi
    $bindir/update-ns -4 -6 $info_mode

  else ## just a simple vassal
    ## 1>&2 echo "we are a vassal"
    $bindir/update-ns -6 $info_mode

  fi
}

info_mode=''
export start_radvd=''
case $1 in
  fwd|forward)
     echo 1 > /proc/sys/net/ipv6/conf/all/forwarding
     start_radvd=yes    # start it _after_ the config file has been created
     start
    ;;
  start|restart)
     start
    ;;
  info)
     info_mode="-v -n" start
    ;;
  stop)
    ip tunnel del 6to4 2>/dev/null || true
    ;;
  *)
    1>&2 echo "Usage:"
    1>&2 echo "  $0 start|forward|stop|restart|info"
    1>&2 echo "  gw64=yes $0 start # sets up gateway"
    1>&2 echo "      # (as opposed to a mere vassal)"
    1>&2 echo "Usage: $0 start|forward|stop|restart|info"
    exit 1
    ;;
esac
