#!/bin/bash
#
# Setup initial hurd translators
#
# This script tries to setup a reasonable set of translators for a newly
# untarred hurd filesystem (since tar currently isn't able to do it).
#
# By passing in a value in the environment variable ROOT, an alternate root
# filesystem may be setup.
#

# A list of likely mach devices to try
DISK_DEVS="`eval echo {s,h}d{0,1,2,3,4}{a,b,c,d,e,f,g,h}`"
NET_DEVS="`eval echo {eth,ne,wd,ul}{0,1,2,3,4}`"

ROOT=${ROOT:-/}
case "$ROOT" in
  /)  PFX="";;
  *)  PFX="$ROOT";;
esac

DEV=${DEV:-/dev}
SERVE=${SERVE:-$PFX/servers}

PDEV=$PFX$DEV
SOCK=$SERVE/socket

function st {
  /bin/settrans -c "$@"
}
function gt {
  /bin/showtrans 2>/dev/null "$@"
}

# Test to see whether a node has a translator
function tp {
  /bin/showtrans -s 2>/dev/null "$@"
}

# Make a device (MAKEDEV uses $_CWD as the device directory)
function md {
 (cd $PDEV && _CWD=$DEV $PDEV/MAKEDEV "$@")
}

function devs {
  /bin/devprobe "$@"
}

PATH=/bin

echo '(For most prompts, `none'\'' is also a valid input)'

# Setup pflocal first, since the shell wants to use it
if tp $SOCK/1; then
  echo "PFLOCAL translator present."
else
  echo "Setting PFLOCAL translator..."
  st $SOCK/1 /hurd/pflocal
fi

if tp $PDEV/console && tp $PDEV/null && tp $PDEV/fd; then
  echo "Standard devices already present."
else
  echo "Making standard devices..."
  md std
fi

# See which disk devices might need creating
DISK_DEVS="`devs $DISK_DEVS`"
if test "$DISK_DEVS"; then
  echo "Mach disk devices found: `echo $DISK_DEVS`"
else
  echo "No mach disk devices found!"
fi

ALREADY=''
MAYBE=''
for D in $DISK_DEVS; do
  if tp $PDEV/r$D; then
    ALREADY="${ALREADY:+$ALREADY }$D"
  else
    MAYBE="${MAYBE:+$MAYBE }$D"
  fi
done
if test "$ALREADY"; then 
  echo "Disk devices with nodes in $PDEV: $ALREADY"
fi
if test "$MAYBE"; then
  echo -n "Create device nodes in $PDEV for: [$MAYBE] "; read CREATE
  if [ "$CREATE" != none ]; then
    md ${CREATE:-$MAYBE}
  fi
fi

NET_DEVS="`devs $NET_DEVS`"
if test "$NET_DEVS"; then
  echo "Mach network devices found: $NET_DEVS"
else
  echo "No mach network devices found."
fi

NET_TRANS="`gt $SOCK/2`"
if test "$NET_TRANS"; then
  echo "PFINET translator present: $NET_TRANS"
  echo -n "Change PFINET translator? [n] "; read yn
  case "$yn" in
    [Yy]*)
      read dummy DEF_NET_ADDR DEF_NET_DEV <<EOF
$NET_TRANS
EOF
      ;;
    *)
      DEF_NET_DEV=skip;;
  esac
else
  DEF_NET_DEV="`devs -first $NET_DEVS`"
  DEF_NET_DEV="${DEF_NET_DEV:-none}"
  DEF_NET_ADDR="none"
fi

if [ "$DEF_NET_DEV" != skip ]; then
  echo -n "Network device: [$DEF_NET_DEV] "; read NET_DEV
  NET_DEV="${NET_DEV:-$DEF_NET_DEV}"
  if [ "$NET_DEV" != none ]; then
    echo -n "Network address: [$DEF_NET_ADDR] "; read NET_ADDR
    NET_DEV="${NET_DEV:-$DEF_NET_DEV}"
    if [ "$NET_ADDR" != none ]; then
      st $SOCK/2 /hurd/pfinet $NET_ADDR $NET_DEV
    else
      echo "PFINET translator not set."
    fi
  fi
fi