#!/bin/sh
# (setq skeleton-pair t)

set -e

# first, source /usr/share/debconf/confmodule

. /usr/share/debconf/confmodule

# db_purge 


# definition of internal functions:
# (to find the end of function defining, look for end)

grep_var () {
  # grep vor a variable assignment to variable $1 in file $2.
  # return the value that is assigned inside double quotes.
  egrep ^[[:blank:]]*$1= $2 | sed -e 's/.*"\([^#]*\)".*/\1/' || true
  # we are set -e, hence the || true
}

restore_false_links(){
  FALSE_LINKS=false
  # is resolv.conf a link to netenv_default, with an underscore instead of dash?
  if [ X`readlink /etc/resolv.conf` = X/etc/resolv.conf.netenv_default ]; then
    # is the target non-existent, that is: Is it stale as expected?
    if [ ! -r `readlink /etc/resolv.conf` ]; then
      # o.k., there is one stale link, let's look whether we can fix that:
      FALSE_LINKS=true
      # is the old file still there?
      if [ -f /etc/resolv.conf.netenv-default ]; then
	# yes, it is there, we remove the link
	rm /etc/resolv.conf
	# put the original file back in its place
	mv /etc/resolv.conf.netenv-default /etc/resolv.conf
	echo "Netenv: Restored old resolv.conf (Bug #225582)."
      else
	# the original file could not be found, we cannot resolve the situation.
	echo "Problems cleaning up wrong links for resolv.conf (Bug #225582)."
	echo "Correct installation, removal or purge of netenv might"
	echo "require manual action."
      fi
    fi
  fi
  # now the same for interfaces - is it a link to a file with underscore?
  if [ X`readlink /etc/network/interfaces` = X/etc/network/interfaces.netenv_default ]; then
    # and is the link stale (target nonexistent)?
    if [ ! -r `readlink /etc/network/interfaces` ]; then
      # o.k., another one.
      FALSE_LINKS=true
      # can we fix it - is the old file still there?
      if [ -f /etc/network/interfaces.netenv-default ]; then
	# yes, it's there, we remove the stale link
	rm /etc/network/interfaces
	# and put the original file back
	mv /etc/network/interfaces.netenv-default /etc/network/interfaces
	echo "Netenv: Restored old interfaces (Bug #225582)."
      else
	# the original file could not be found, we cannot resolve the situation.
	echo "Problems cleaning up wrong links for interfaces (Bug #225582)."
	echo "Correct removal or purge of netenv might require manual action"
      fi
    fi
  fi
  # the cause of all that mess was a typo in the setup-default script.
  BAD_SCRIPT=/etc/netenv/setup-default
  # is it still called? Only look in non-commented lines
  if [ -f $BAD_SCRIPT ]; then
    if grep -v ^#  $BAD_SCRIPT | grep netenv_default >/dev/null 2>&1; then
      tempfile=`tempfile`
      trap 'rm -f $tempfile' 0 HUP INT QUIT PIPE TERM
      # replace in non-commented lines
      sed -e 's/^\([[:space:]]*[^#]*\)netenv_default/\1netenv-default/g' < $BAD_SCRIPT >$tempfile
      rm $BAD_SCRIPT
      mv $tempfile $BAD_SCRIPT
      echo "Netenv: Corrected buggy setup-default file (Bug #225582)."
    fi
  fi
  # if we found false links, we know that the setup using links was 
  # chosen (but never worked). To enable it again in postinst, we now 
  # write a temporary file; postinst will look for it.
  if [ $FALSE_LINKS = true ]; then
    touch /var/tmp/netenv_upgrade_restored-symlinks
  fi
}

check_interfaces () {
  INTERFACES=/etc/network/interfaces
  TMP_INTERFACES=`tempfile 2> /dev/null`
  trap 'rm -f $TMP_INTERFACES' 0 HUP INT QUIT PIPE TERM
  TMP2_INTERFACES=`tempfile 2> /dev/null`
  trap 'rm -f $TMP2_INTERFACES' 0 HUP INT QUIT PIPE TERM
  # filter out commented and blank lines, get the 5 lines 
  # following the eth0 entry. (the || true is necessary because we are set -e)
  egrep -v '^[[:blank:]]*$|^#' $INTERFACES 2>/dev/null | grep -A 5 "iface eth0" > $TMP_INTERFACES || true
  # how many lines are there really (maximum is 6)?
  LINES=`wc -l $TMP_INTERFACES  | cut -d " " -f 5`
  # there can be up to 5 options. But the next iface stanza might also
  # start earlier.  So, do we have an other iface entry in here? If
  # yes, kick out the last lines, one by one, until there's no "iface"
  # left.
  while grep -v "iface eth0" $TMP_INTERFACES | grep iface > /dev/null; do
    LINES=$(($LINES - 1))
    head -n $LINES $TMP_INTERFACES > $TMP2_INTERFACES
    cat $TMP2_INTERFACES > $TMP_INTERFACES
  done
  rm $TMP2_INTERFACES
  # Now, how eth0 defined? The sed expression should yield static, dhcp, or bootp.
  # It is kind of complicated, because there may be different amount of different 
  # kind of whitespace between the keywords, and a comment after it.
  ETH0_METHOD=`grep "iface eth0" $TMP_INTERFACES | \
    sed -e \
's/[[:space:]]*iface[[:space:]][[:space:]]*eth0[[:space:]][[:space:]]*inet[[:space:]][[:space:]]*\(.*\)[[:space:]]*.*/\1/'`
  case $ETH0_METHOD in
    static)
      # yes, it's static. So we need an address field. Is it there? 
      if grep address $TMP_INTERFACES >/dev/null 2>&1; then 
        # o.k., it seems eth0 is configured in /etc/network/interfaces.
        # is there also a readable resolv.conf?
	if [ -r /etc/resolv.conf ]; then
          # yes, so we can use this information
	  IP_IN_INTERFACES=true; 
	fi
      fi
      ;;
    dhcp|bootp)
      # there's no "must" keywords here. We assume it is configured correctly
      IP_IN_INTERFACES=true; 
      ;;
  esac
  rm $TMP_INTERFACES
}

is_true () {
  # this is what the pcmcia packages recognize as true
  [ "$1" = "y" -o "$1" = "Y" -o "$1" = "yes" -o "$1" = "YES" ]
}


check_network_opts () {
  NETOPTS=/etc/pcmcia/network.opts
  if [ -r $NETOPTS ]; then
    # are the necessary variables set in this file
    # (either ip address, or bootp/dhcp)
    PCMCIA_IPADDR=`grep_var IPADDR $NETOPTS`
    PCMCIA_BOOTP=`grep_var BOOTP $NETOPTS`
    PCMCIA_DHCP=`grep_var DHCP $NETOPTS`
    if [ -n "$PCMCIA_IPADDR" ]; then
      IP_IN_PCMCIA=true;
    elif is_true $PCMCIA_BOOTP; then
      IP_IN_PCMCIA=true;
    elif is_true $PCMCIA_DHCP; then
      IP_IN_PCMCIA=true;
    fi
  fi
}

# end of function defining

# variables used:
NODE=`uname -n`

# there was a bug in 0.94.3-1 which might have messed up the
# configuration. We check for that and restore the old files, 
# if possible.
restore_false_links

# figure out whether there is an existing configuration
CONFS=`ls -1 /etc/netenv/${NODE}* 2>/dev/null|wc|awk '{print $1}'` || true

# here we go...
if [ $CONFS -gt 0 ]; then
# it seems there is an old configuration yet. 
# Should we keep it?
# (this question has to be set to unseen first, unless explicitly specified)
  db_get netenv/showagain
  if [ X$RET = Xfalse ]; then
    :
  else
    db_fset netenv/is_configured0 seen false || true
    db_fset netenv/showagain seen false || true
  fi
  db_subst netenv/is_configured0 NODE ${NODE} || true
  # so, should we keep it?
  db_input medium netenv/is_configured0 || true
  db_go
else
# no configuration files found. Ask how to create them, or to disable netenv
  db_set netenv/is_configured0 false || true
fi

# now look whether we in fact should change the configuration 
# (either because there is none, or because we have been asked to)
db_get netenv/is_configured0 || true
if [ "$RET" = "false" ]; then
# first find out wether network information is stored in /etc/network/interfaces
# or in /etc/pcmcia/network.opts, or both or none
  IP_IN_INTERFACES=false
  IP_IN_PCMCIA=false
  check_interfaces
  check_network_opts
# compare what we've found:
  AUTO_OK=false
  DISABLE_REASON=
  AUTO_METHOD=
  if [ "$IP_IN_INTERFACES" = "true" ]; then
    # we found can use /etc/network/interfaces.
    if [ "$IP_IN_PCMCIA" = "true" ]; then
      # we also found that we can use network.opts. There is no way to 
      # find out which is correct, so we do not automatically configure
      AUTO_OK=false
      DISABLE_REASON=twoconfs
    else
      # only interfaces, automatic is o.k.
      AUTO_OK=true
      AUTO_METHOD=interfaces
    fi
  else
    # no configuration found in network/interfaces
    if [ "$IP_IN_PCMCIA" = "true" ]; then
      # but it's there in network.opts, automatic is o.k.
      AUTO_OK=true
      AUTO_METHOD=pcmcia
    else
      # no conf at all.
      AUTO_OK=false
      DISABLE_REASON=noconf
    fi
  fi

# can the configuration we found be used?
  if [ "$AUTO_OK" = "true" ]; then
# yes, it can. Still we first ask wether this is desired.
    db_input medium netenv/auto_configure || true
    db_go
    db_get netenv/auto_configure
    if [ "$RET" = "Use current settings" ]; then
      # the user asked us to use the settings we found for automatic configuration
      case "$AUTO_METHOD" in
	# now we store the method to use (interfaces vs. network.opts) in debconf,
	# for use by postinst.
	interfaces)
	  db_set netenv/auto_method interfaces 
	  # also we inform the user about the method chosen, and how to 
	  # generate more configurations
	  db_subst netenv/info_interfaces NODE ${NODE}
	  db_input high netenv/info_interfaces || true
	  ;;
	pcmcia)
	  db_set netenv/auto_method pcmcia
	  # here we inform the user what he still has to do to make it work.
	  db_input critical netenv/info_pcmcia || true
	  ;;
	*) exit 1
      esac
      db_go
    fi
  else
# if we can't use the current configuration, we simply
# disable netenv on boot:
    db_set netenv/auto_configure "Disable for now" || true		
    # and tell the user why.
    case "$DISABLE_REASON" in
      noconf)
	db_input high netenv/noconf || true ;;
      twoconfs)
	db_input high netenv/twoconfs || true ;;
      *) exit 1
    esac
    db_go
  fi
else
  # if there was an existing configuration, we ask the user whether he doesn't
  # want to be bothered again.
  db_input medium netenv/showagain || true
  db_go
fi
