#!/bin/sh

#DEB_HOST_GNU_SYSTEM=`dpkg-architecture -qDEB_HOST_GNU_SYSTEM`
DEB_HOST_GNU_CPU=`dpkg-architecture -qDEB_HOST_GNU_CPU`
#DEB_HOST_GNU_TYPE=`dpkg-architecture -qDEB_HOST_GNU_TYPE`

usage() {
      echo "Usage: $0 [ -t path ] [ -s system ] [ -c cpu ] [ -d distrib ]"
      echo
      echo "  system is one of linux-gnu, gnu, or kfreebsd-gnu."
      echo "  cpu is a GNU CPU (e.g. i386 or x86_64)."
      echo "  distrib is a distribution name ((old)*stable, testing, unstable)."
}

while [ $# -ge 1 ]
do
  case $1 in
    -t)
      shift
      TARGET=$1
      if [ -z "$TARGET" ]
      then
	echo "-t needs a target path"
	exit 1
      fi
      shift;;
    -s)
      shift
      DEB_TARGET_GNU_SYSTEM=$1
      if [ -z "$DEB_TARGET_GNU_SYSTEM" ]
      then
	echo "-s needs a target system (linux-gnu, gnu or kfreebsd-gnu)"
	exit 1
      fi
      shift;;
    -c)
      shift
      DEB_TARGET_GNU_CPU=$1
      if [ -z "$DEB_TARGET_GNU_CPU" ]
      then
	echo "-c needs a target CPU (e.g. i386 or x86_64)"
	exit 1
      fi
      shift;;
    -d)
      shift
      RELEASE=$1
      if [ -z "$RELEASE" ]
      then
	echo "-d needs a distribution name ((old)*stable, testing, unstable)"
	exit 1
      fi
      shift;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unrecognized: $1"
      usage
      exit 1
      ;;
  esac
done

if [ -z "$TARGET" ]
then
  exec 3>&1
  TARGET=`dialog --inputbox "What is the target directory?" 0 0 "/root/jail" 2>&1 1>&3`
  retval=$?
  exec 3>&-
  case $retval in
      0) ;;
      1|255) exit ;;
  esac
fi

if [ -z "$DEB_TARGET_GNU_SYSTEM" ]
then
  exec 3>&1
  DEB_TARGET_GNU_SYSTEM=`dialog --menu "Target Debian system?" 0 0 4 linux-gnu GNU/Linux gnu GNU/Hurd kfreebsd-gnu GNU/kFreeBSD 2>&1 1>&3`
  retval=$?
  exec 3>&-
  case $retval in
      0) ;;
      1|255) exit ;;
  esac
fi

if [ -z "$DEB_TARGET_GNU_CPU" ]
then
  [ "$DEB_TARGET_GNU_SYSTEM" = gnu ] && DEB_HOST_GNU_CPU=i386

  exec 3>&1
  DEB_TARGET_GNU_CPU=`dialog --inputbox "Target CPU?" 0 0 "$DEB_HOST_GNU_CPU" 2>&1 1>&3`
  retval=$?
  exec 3>&-
  case $retval in
      0) ;;
      1|255) exit ;;
  esac
fi

case $DEB_TARGET_GNU_SYSTEM in
  linux-gnu)
    ;;
  *)
    RELEASE=unstable
    ;;
esac

if [ -z "$RELEASE" ]
then
  exec 3>&1
  RELEASE=`dialog --menu "Target Debian distribution?" 0 0 4 oldoldstable Old-old-stable oldstable Old-stable stable Stable testing Testing unstable Unstable 2>&1 1>&3`
  retval=$?
  exec 3>&-
  case $retval in
      0) ;;
      1|255) exit ;;
  esac
fi

#if [ "$DEB_TARGET_GNU_SYSTEM" = "gnu" ] ; then
#	exec 3>&1
#	FOO=`dialog --defaultno --yesno "Create a /usr -> . symlink?" 0 0 2>&1 1>&3`
#	retval=$?
#	exec 3>&-
#	0 is yes, 1 is no
#	case $retval in
#	    0) ln -s . $TARGET/usr ;;
#	    1) ;;
#	    255) exit ;;
#	esac
#fi

if [ -f /usr/bin/eatmydata ]
then
  eatmydata=/usr/bin/eatmydata
else
  eatmydata=
fi

$eatmydata /usr/share/crosshurd/makehurddir.sh "$TARGET" "$DEB_TARGET_GNU_CPU" "$DEB_TARGET_GNU_SYSTEM" "$RELEASE"

