#!/bin/ash
#
# Wizard for easy PLD Linux installation setup.
#
# (C) 2001, 2002 Michal Moskal <malekith@pld-linux.org>
#
# This file can be modified and/or redistributed under
# the terms of GPL version 2 (without any options :^).
#
# Few notes: this script is only aimed to handle 95% of hardware
# configuration (i.e. few from hundreds possible, but valid for
# 95% of average systems). For remaining 5% see regular ui-main,
# and/or vi. However this level of portability has not been reached
# yet :^]
#
# I know it looks stupid, [ Next >> ] and so on, but this way,
# I hope, using it is obvious to average high school student, who's 
# just basically computer literate.
#
# WARNING: Berkeley Quality Software inside.
#

# temporary for testing
export PATH=.:..:$PATH
add_title="_The _Sorcerer"
. installer-functions
. ui-functions

#tmpdir=/tmp
#if [ -d $HOME/tmp ] ; then
#  tmpdir=$HOME/tmp
#fi
#logfile=`mktemp $tmpdir/ui-logfile-XXXXXX`

find_config_paths "$@"
load_or_create_config

if [ "$STEP" ] ; then
  step=$STEP
else
  step=prep
fi

sysconf=

# helpers to get to next/prev step
step_list () {
  echo -n "prep source1 source2 "
  if [ "$source" = net -o "$source" = nfs ] ; then
    echo -n "netdev netconf netip "
  fi
  echo -n "dest profile pkgs pkgsopt "
  # sysconfig:
  echo -n "sysnet sysnetip sysnetdev hostname rootpass user lang boot bootdev "
  # finish...
  echo "run fini"
}

next_step () {
  local f last

  last=
  
  for f in $(step_list) ; do
    if test $last ; then
      echo $f
      return
    fi
    if [ "$f" = "$step" ] ; then
      last=x
    fi
  done
}

prev_step () {
  local f last

  last=
  
  for f in $(step_list) ; do
    if [ "$f" = "$step" ] ; then
      echo $last
      return
    fi
    last=$f
  done
}


step_no () {
  local f i

  i=1
  
  for f in $(step_list) ; do
    if [ "$f" = "$step" ] ; then
      echo $i
      return
    fi
    i=$(($i+1))
  done
}

###
# prep
###

pre_prep () {
  # skip it on real system (testing)
  #[ $real_system = no ] || return 1
}

# This was already displayed in setup...
# $(nls "For more information about PLD please visit our WWW pages")<br>
# $(nls "at http://www.pld.org.pl. Also, if you have any remarks")<br>
# $(nls "please send them to <feedback@pld.org.pl>.")<br><br>

display_prep () {
  cat <<EOF
$(nls "Welcome to The Sorcerer!")<br><br>
$(nls "This program will help you in PLD Linux installation.")<br>
$(nls "Running it is the easiest way to install PLD, we know,")<br>
$(nls "however you should note, that this program enables you to")<br>
$(nls "use just a fraction of PLD Linux installer capabilities.")<br>
$(nls "If you are unable to install using it (for example because")<br>
$(nls "of unsupported hardware configuration), try generic way")<br>
$(nls "with '%s' item in main menu." "$(nls "Regular setup UI")")<br>
EOF
}

post_prep () {
}

###
# source1
###
pre_source1 () {
}

display_source1 () {
  cat <<EOF
$(nls "Source of installation:")
<br>
<meta active=source>
<br>
<menu id=source res=1002 selected=$source>
<item id=cdrom>_cdrom: $(nls "CD-ROM device")
<item id=net>_net: $(nls "network server (ftp, http)")
<item id=nfs>_nfs: $(nls "NFS server")
<item id=disk>_disk: $(nls "Hard disk partition")
</menu>
<br>
$(nls "Please select device you are going to install from, then press <br>Enter or Next >>.")
EOF
}

post_source1 () {
}

###
# source2
###

pre_source2 () {
  local ok
  
  if [ $source = cdrom ] ; then
    ok=
    autocdrom=

    if [ "$real_system" = no ] ; then
      load_module ide-mod
      load_module ide-probe-mod
      load_module cdrom
      load_module ide-cd
      if [ $KERNEL_VERCODE -ge 4 ] ; then
        load_module zlib_inflate
      fi
      load_module isofs
      make_ide_cd_devfs_links
    fi
    
    if [ -d /proc/ide ] ; then
      for f in /proc/ide/hd* ; do
        if [ -f $f/media ] && [ "$(cat $f/media)" = "cdrom" ] ; then
          autocdrom="$autocdrom /dev/`basename $f`"
        fi
      done
    fi

    autocdrom=$(echo "$autocdrom" | sed -e 's/^ //')
 
    if grep -q /src /proc/mounts ; then
      umount /src
    fi

    for f in $autocdrom ; do
      if mount -t iso9660 -o ro $f /src > /dev/null 2> /dev/null ; then
        if [ -d /src/PLD/inst/pkg ] ; then
          source_device=$f
	  source_dir=/
	  source_filesystem=iso9660
	  ok=x
        fi
	rm -f /tmp/is-mini-iso
	if is_mini_iso ; then
	  echo yes >/tmp/is-mini-iso
	fi
        umount /src
      fi
    done
  
    if test "$ok" ; then
      return 1 # skip section, not needed.
    fi
  fi

  return 0
}

det () {
  if echo " $autocdrom " | grep -q " $1 " ; then
    nls "(detected)"
  fi
}

cdrom_source () {
    cat <<EOF
$(nls "CD-ROM device"):
<menu id=source_device res=1002 selected="$autocdrom">
<item id=/dev/hda>/dev/hda $(nls "(Primary Master (not likely))") $(det /dev/hda)
<item id=/dev/hdb>/dev/hdb $(nls "(Primary Slave)") $(det /dev/hdb)
<item id=/dev/hdc>/dev/hdc $(nls "(Secondary Master)") $(det /dev/hdc)
<item id=/dev/hdd>/dev/hdd $(nls "(Secondary Slave)") $(det /dev/hdd)
<item id=/dev/scd0>/dev/scd0 $(nls "(SCSI CD-ROM #0)") $(det /dev/scd0)
<item id=/dev/scd1>/dev/scd1 $(nls "(SCSI CD-ROM #1)") $(det /dev/scd1)
<item id=/dev/scd2>/dev/scd2 $(nls "(SCSI CD-ROM #2)") $(det /dev/scd2)
<item id=/dev/scd3>/dev/scd3 $(nls "(SCSI CD-ROM #3)") $(det /dev/scd3)
</menu>
EOF
  
  cat <<EOF
<br><br>
$(nls "Directory on the CD"): <input id=source_dir caption='$source_dir'>
<br><br>$(nls 'Better leave this option with "/", unless you are not using')
<br>$(nls 'official PLD ISO Image.')
EOF
  # hmm.. we might want to allow user changing this
  source_filesystem=iso9660
}

net_source () {
  cat <<EOF
$(nls "FTP or HTTP server URL:") <input caption="$source_device" id=source_device> 
<button caption="$(nls "_List")" res=1><br>
$(nls "Press button to choose mirror nearby.")
<br><br>
$(nls "Source exact directory:") <input id=source_dir caption="$source_dir">
<br>$(nls "If you are not sure about exact directory, leave it untouched.")
<br><br>$(nls "HTTP/FTP proxy to use: ")
<input caption="$net_proxy" id=net_proxy><br>
$(nls "Example proxy: %s" "http://squid.foobar.org:3128/")
EOF
  source_filesystem=net
}

nfs_source () {
  cat <<EOF
$(nls "Remote-machine:/exported/directory:")<br>
<input caption="$source_device" id=source_device><br>
$(nls "In place of remote-machine you can use numerical IP, or hostname.")<br><br>
$(nls "Directory inside /exported/directory, that contains RPMS/ and<br>inst/pkg/ directories:")
<br><input id=source_dir caption="$source_dir"><br><br>
$(nls 'Example: You install on machine "gont" from "roke" over nfs. ')<br>
$(nls 'If you have RPMS/ and inst/pkg/ directories on "roke", in ')<br>
$(nls '/home/ftp/pub/PLD, and its /etc/exports file reads: ')<br>
$(nls '"/home/ftp gont(ro)", you need to say: "roke:/home/ftp/" in ')<br>
$(nls 'the first input line and "/pub/PLD/" in the second.')<br>
EOF
  source_filesystem=nfs
}

disk_source () {
  # this could display some more info, allow some menu selection...
  cat <<EOF
$(nls 'Device (partition) to mount :') <input caption="$source_device" id=source_device><br>
$(nls '/dev/hdb1, /dev/sda3 or something like that.')<br><br>
$(nls 'Directory on mounted device :') <input caption="$source_dir" id=source_dir><br>
$(nls 'Where PLD/RPMS and PLD/inst/pkg directories can be found.')<br><br>
$(nls '          Filesystem to use :') <input caption="$source_filesystem" id=source_filesystem><br>
$(nls 'Something like ext2, vfat (used by windows).')<br><br>
EOF
}

display_source2 () {
  case $source in
    cdrom)
      cdrom_source
      ;;
    net )
      net_source
      ;;
    nfs )
      nfs_source
      ;;
    disk )
      disk_source
      ;;
  esac
}

set_scsi_hostadapters () {
  if test -z "$scsi_hostadapters" ; then
    scsi_hostadapters=auto
  fi

  if test "x$scsi_hostadapters" = "xauto"; then
    adapters=`detect-scsi-devices -m || :`
    if test "$adapters" ; then
      return 0 # ok, detected
    fi
  else
    # ok, some other module..
    return 0
  fi

  # oops... wasn't able to detect host adapter, ask the user, maybe
  # it was an error...
  
  if yes_no no $(nls "Are you sure you have SCSI controller installed?") ; then
    info "$(nls "You can select hostadapter from list.<br>Select '%s' from main menu to do so." \
    	  "$(nls "Regular setup UI")")"
    #get_input scsi_hostadapters "" $(nls "Please enter scsi hostadapter(s) modules:") 
    scsi_hostadapters=unknown
    return 0
  else
    # ok, it was an error, return error, so we'll get back
    return 1
  fi
}

post_source2 () {
  case $source in
    net )
      case $res in
        1)
	  source_device=$(ui-mirror)
	  return 1
	  ;;
      esac
      ;;
    cdrom | disk )
      case $source_device in
        /dev/sd* | /dev/scsi/* )
	  set_scsi_hostadapters
	  ;;
      esac
  esac
}

###
# netdev
###
pre_netdev () {
  # we should be able to set this...
  net_device=eth0
  net_v6=no
}

display_netdev () {
  local mods
 
  if [ $real_system = no ] ; then
    mods=$(detect-net-devices -m || :)
  else
    mods=$(cd ../pci; ./sh-scan-pci -m || :)
  fi

  if [ "$mods" = "" ] ; then
    # couldn't detect...
    if [ -x /bin/probe ] ; then
      echo "<meta active=i_have_pcmcia>"
    else
      echo "<meta active=net_device_module>"
    fi
    echo "<menu id=net_device_module selected='$net_device_module' res=1002>"
    grep -vs '^~' /etc/eth.list.in | while read line; do
      dev=`echo $line | sed 's/\.o|.*//' | sed 's/_/__/'`
      dev_esc=`echo $dev | sed 's/_/__/'`
      desc=`echo $line | sed 's/[^|]*|//' | sed 's/|.*//'`
      echo "<item id=\"$dev\">$dev_esc: _$desc"
    done
    echo "</menu>"
    echo "$(nls "Extra options (irq=10, etc.)"):" \
         "<input id=net_device_module_options caption='$net_device_module_options'>"
  else
    if echo $mods | grep -q ' ' ; then
      nls "Detected network devices: %s<br>" "$mods"
      nls "First one will be used.<br>"
      # TODO: maybe allow choice here?
    else
      nls "Detected network device: %s" "$mods"
    fi
    echo "<br><br>"
    echo "$(nls "Module                      "): <input id=net_device_module caption='auto'><br>"
    nls "Leave this on 'auto'.<br><br>"
    echo "$(nls "Extra options (irq=10, etc.)"):" \
   	"<input id=net_device_module_options caption='$net_device_module_options'><br>"
    nls "If unsure, leave this blank."
  fi

  echo "<br><button id=i_have_pcmcia res=1 caption='$(nls "I have _PCMCIA card.")'>"
}

post_netdev () {
  case "$res" in
    1 )
      if [ -x /bin/probe ] ; then
        net_device_module=auto
        net_device_module_options=
        pcmcia_controler=auto
        res=1002
      else
        info "$(nls "If you have PCMCIA card you should<br>use bootdisk_pcmcia.img.")"  
	return 1
      fi
      ;;
  esac
}

###
# netconf
###
pre_netconf () {
}

method=static

display_netconf () {
  if [ "$net_ipaddr" = dhcp ] ; then
    method=dhcp
  fi
  cat <<EOF
$(nls "Please select method of network configuration for this host:")
<br><br>
<meta active=method>
<menu id=method selected="$method" res=1002>
<item id=static>$(nls "Use _Static IP")
<item id=dhcp>$(nls "Get IP from _DHCP server")
</menu>
EOF
}

post_netconf () {
}

###
# netip
###
pre_netip () {
  case "$method" in
    dhcp )
      net_ipaddr=dhcp
      return 1 # skip
      ;;
  esac
}

display_netip () {
  cat <<EOF
$(nls "IP address :") <input caption="$net_ipaddr" id=net_ipaddr> 
 / <input caption="$net_prefix" id=net_prefix width=5><br>
$(nls "Gateway    :") <input caption="$net_gateway" id=net_gateway><br>
$(nls "DNS        :") <input caption="$net_dns" id=net_dns><br>
$(nls "Device     :") <input caption="$net_device" id=net_device><br>
<br>
$(nls "Example config (for host behind masquerade):")<br>
$(nls "IP address :  192.168.1.41 / 24")<br>
$(nls "Gateway    :  192.168.1.1")<br>
$(nls "DNS        :  194.204.159.1 194.204.152.34")<br>
EOF
}

post_netip () {
}

###
# dest
###
pre_dest () {
  ram_size=$(($(ls -l /proc/kcore | ( read x1 x2 x3 x4 size rest ; echo $size ))/(1024*1024)+1))
  swap_size=$(($ram_size*2))
}

display_dest () {
  nls "Now, you can either choose default partitioning scheme<br>"
  nls "or alternatively (if you have ever partitioned Linux disk,<br>"
  nls "or are not happy to loose all your partitions), setup<br>"
  nls "partitions manually.<br><br>"
  nls "Warning! Partitioning software works in real time,<br>"
  nls "it does not wait for exit to save changes.<br><br>"
cat <<EOF
<meta active=way>
<menu id=way res=1002>
<item id=manual>$(nls "Setup partitions _manually")
<item id=default>$(nls "_Erase all partitions, and setup _default (see below)")
</menu><br>
EOF

  nls "Default scheme is:<br>"
  # maybe remove /boot altogether?
  nls "%s on %s (%d Mb)<br>" "/dev/hda1" "/boot" "20"
  nls "%s on %s (%d Mb)<br>" "/dev/hda2" "swap" "$swap_size"
  nls "%s on %s (rest)<br>" "/dev/hda3" "/" 
}

save_default_part () {
  # clean up
  id=1
  while [ $id -lt 100 ] ; do
    eval dest_part${id}_mnt_point=
    id=$(($id+1))
  done

  dest_part1_device=/dev/hda1
  dest_part1_mnt_point=/boot
  dest_part1_filesystem=ext2
  dest_part1_format_partition=yes
  dest_part1_options=defaults
  dest_part1_format_options=
  dest_part1_size=20
  
  dest_part2_device=/dev/hda2
  dest_part2_mnt_point=swap
  dest_part2_filesystem=swap
  dest_part2_format_partition=yes
  dest_part2_options=defaults
  dest_part2_format_options=
  dest_part2_size=$swap_size
  
  dest_part3_device=/dev/hda3
  dest_part3_mnt_point=/
  dest_part3_filesystem=ext2
  dest_part3_format_partition=yes
  dest_part3_options=defaults
  dest_part3_format_options=
  dest_part3_size='100% of free'
  
  dest_devices=/dev/hda
  dest_devices_actions=make_new
  
  save_config
}

did_select_dest_devices=

select_dest_devices () {
  if test "$did_select_dest_devices" && \
     test "$(echo "$dest_devices" | sed -e 's/ //g')" && \
     yes_no yes $(nls "Do you want to keep dest_devices with:<br>%s" "$dest_devices") ; then
    return 0
  fi
  
  did_select_dest_devices=yes

  tmp=$(echo "$dest_devices" | sed -e 's|/dev/[hs]d[a-d]||g' | \
        sed -e 's@/dev/\(ida\|cciss\|rd\)/c0d0@@g' | \
	sed -e 's@/dev/ataraid/d0@@g' | sed -e 's| ||g' )
  if test "$tmp" ; then
    # cannot handle in menu
    get_input dest_devices "$dest_devices" $(nls "Please enter dest_devices:")
  else
    dial <<EOF
<meta title='$(nls "Dest devices selection")'>
<br>
$(nls "Please select drives you want to install to.")<br>
$(nls "If you don't know which drive you have, just")<br>
$(nls "select '/dev/hda' and press [ Ok ].")<br><br>
<menu id=dd checked="$dest_devices">
$(
  for f in /dev/hda /dev/hdb /dev/hdc /dev/hdd \
           /dev/sda /dev/sdb /dev/sdc /dev/sdd \
	   /dev/cciss/c0d0 /dev/ida/c0d0 /dev/rd/c0d0 \
	   /dev/ataraid/d0 /dev/i2o/hda ; do
    echo "<item id=$f checked=0>$f $(disk_name $f)"
  done
)
</menu>
$ok_cancel <button res=3 caption="$(nls _Custom)">
EOF
    if [ "$res" = 1 ] ; then
      if echo "$dd" | grep -q "^ *$" ; then
        return 1
      fi
      dest_devices="$dd"
    elif [ "$res" = 3 ] ; then
      get_input dest_devices "$dest_devices" $(nls "Please enter dest_devices:")
      return
    else
      did_select_dest_devices=
      return 1
    fi
  fi

  return 0
}

post_dest () {
  case "$res" in
    1002 )
      case "$way" in
        manual )
	  if select_dest_devices ; then
	    save_config
	    echo -n > /tmp/load_parted_result
            ui-parted2 -C $conffile -S $sysconffile
	    if [ "$(cat /tmp/load_parted_result)" = oops ] ; then
	      if yes_no yes $(nls "As I failed to load parted, would you like to<br>be sent back to source configuration?") ; then
	        step=source1
		return 1
	      fi
	    fi
	    load_config
	  else
	    return 1
	  fi
	  res=1002
	  ;;
	default )
	  if yes_no no $(nls "Are you sure, you want to erase entire disk content?") ; then
	    save_default_part
	    res=1002
	  else
	    res=0
	  fi
	  ;;
	* )
	  die "post_dest(): bad way"
	  ;;
      esac
      ;;
  esac
}

###
# profile
###
last_pkg_set=

pre_profile () {
  if test -f /tmp/is-mini-iso ; then
    info $(nls "You appear to be installing from MINI-ISO.<br>In this case you can only select one of 'MINI-ISO' or 'base' installation profiles.")
  fi
}

md5 () {
  md5sum "$1" | (read sum file; echo $sum)
}

display_profile () {
  if [ "$last_pkg_set" = "" ] ; then
    # if /etc/installer.pkgs contains basic pkgset, we can select it
    # or mini-iso, otherwise config was loaded from disk or created
    # using some other way and we shouldn't touch it unless explicitly
    # told to.
    if [ $(md5 $pkgsetsdir/basic) = $(md5 $pkgsfile) ] ; then
      if test -f /tmp/is-mini-iso ; then
        last_pkg_set=$pkgsetsdir/MINI-ISO
      else
        last_pkg_set=$pkgsetsdir/basic
      fi
    else
      last_pkg_set=$pkgsetsdir/LAST
      cp $pkgsfile $last_pkg_set
    fi
  fi
  echo "<meta active=pkg_set>"
  nls "Please select desired installation profile.<br><br>"
  echo "<menu height=12 id=pkg_set selected='$last_pkg_set' res=1002>"
  for f in $pkgsetsdir/* ; do
    name=$(basename $f)
    if [ "$name" = CVS ] ; then
      continue
    fi
    echo "<item id=$f>_$name"
    size=$(nls "unknown")
    desc1=$(nls "Group %s" "$name")
    desc2=
    case "$name" in
      base )
        desc1=$(nls "Just very basic packages.")
	desc2=$(nls "Don't select unless you're doing embedded system")
	size=$(nls '50MB without docs, just one locale')
	;;
      basic )
        desc1=$(nls "Base PLD Linux installation.")
	size=$(nls '120MB (no docs, 1 locale) - 200MB')
        ;;
      devel )
        desc1=$(nls "Base PLD Linux installation + few development packages.")
        ;;
      gnome-workstation )
        desc1=$(nls "X workstation running GNOME")
	;;
      kde-workstation )
        desc1=$(nls "X workstation running KDE")
	;;
      wm-workstation )
        desc1=$(nls "X workstation running WindowMaker")
	;;
      MINI-ISO )
        desc1=$(nls "Base packages + ppp, poldek.")
	desc2=$(nls "Select this if you're installing from MINI-ISO.")
	size=$(nls '110MB with docs, all locales')
	;;
      LAST )
        desc1=$(nls "Packages, you have selected last time.")
	;;
    esac
    
    echo "<item ghosted=1>    $desc1"
    if [ "$desc2" != "" ] ; then
      echo "<item ghosted=1>    $desc2"
    fi
    echo "<item ghosted=1>    $(nls "Hard disk space required: %s" "$size")"
  done
  echo "</menu>"
}

post_profile () {
  if [ "$res" = 1002 -a "$pkg_set" != "$last_pkg_set" ] ; then
    cp $pkg_set $pkgsfile
    if [ "$pkg_set" != LAST ] ; then
      cp $pkg_set $pkgsetsdir/LAST
    fi
    last_pkg_set=$pkg_set
  fi
}

###
# pkgs
###
pre_pkgs () {
}

display_pkgs () {
  nls "Press enter on [ %s ],<br>" "$(nls "Fine-grained packages selection")"
  nls "if you want it. Otherwise press [ Next >> ].<br><br>"
  echo "<button res=1 caption='_$(nls "Fine-grained packages selection")'>"
}

post_pkgs () {
  case "$res" in
    1 )
      ui-pkgs -P $pkgsfile -C $conffile -G $groupsfile
      cp $pkgsfile $pkgsetsdir/LAST
      res=1002
      ;;
  esac
}

###
# pkgsopt
###
pre_pkgsopt () {
  sysconf=
}

display_pkgsopt () {
  install_docs=1
  if [ "$pkgs_install_docs" = no ] ; then
    install_docs=0
  fi
  
  nls "You are not required to install documentation along with<br>"
  nls "packages. However, it also holds true, that *documentation<br>"
  nls "is good*. :^)<br><br>"
  echo -n "<check id=pkgs_install_docs checked=$install_docs> "
  nls "Yes, I would like to have documentation installed.<br><br>"
  nls "Some of programs are localized, which means they speak<br>"
  nls "other languages besides English. You might not want to install<br>"
  nls "localization files for these programs, or install them just for<br>"
  nls "few languages.<br><br>"
  nls "Enter 'all' in input box below to install all languages (safe<br>"
  nls "choice). Otherwise enter string like 'pl:pl_PL:de:de_DE:en:en_US' to<br>"
  nls "install Polish, German and American English locales.<br><br>"
  nls "Install langs: "
  echo "<input id=pkgs_install_langs caption='$pkgs_install_langs'>"
}

post_pkgsopt () {
}

###
# sysnet
###
pre_sysnet () {
  sysconf=yes
  load_sys_config
}

display_sysnet () {
  load_config
  if [ "$net_ipaddr" = dhcp ] ; then
    nls "Installer will use DHCP for network configuration.<br><br>"
  else
    nls "Installer network settings are:<br><br>"
    nls "Address: %s / %s<br>" "$net_ipaddr" "$net_prefix"
    nls "Gateway: %s<br>" "$net_gateway"
    nls "DNS    : %s<br><br>" "$net_dns"
  fi
  
  load_sys_config
  
  nls "You can either use installer settings for installed box,<br>"
  nls "or choose to configure it differently.<br><br>"
  
  cat <<EOF
<menu id=net_config res=1002 selected="$net_config">
<item id=installer_settings>$(nls "Use installer settings")
<item id=manual>$(nls "Manual")
<item id=dhcp>$(nls "DHCP")
<item id=none>$(nls "no network")
</menu><br>
EOF
  # TODO: we do not allow other net_device...
}

post_sysnet () {
}

###
# sysnetip
###
pre_sysnetip () {
  sysconf=yes
  load_sys_config
  case "$net_config" in
    installer_settings | none | dhcp )
      return 1 # skip
      ;;
  esac
}

display_sysnetip () {
  display_netip
}

post_sysnetip () {
}

###
# sysnetdev
###
pre_sysnetdev () {
  sysconf=yes
  if [ "$net_device" = "" ] ; then
    net_device=eth0
  fi
  case "$net_config" in
    installer_settings | none )
      return 1 # skip
      ;;
  esac
}
  
display_sysnetdev () {
  display_netdev
}

post_sysnetdev () {
  post_netdev
}

###
# hostname
###
pre_hostname () {
  sysconf=yes
  if [ "$net_config" = dhcp -o "$net_ipaddr" = dhcp ] ; then
    return 1 # skip
  fi
}

display_hostname () {
  nls "You should choose hostname and domainname for your system,<br>"
  nls "even if you are not going to use networking, since some<br>"
  nls "programs relay on it.<br><br>"
  echo "$(nls 'Hostname   :') <input id=net_hostname caption='$net_hostname'><br>"
  echo "$(nls 'Domain name:') <input id=net_domainname caption='$net_domainname'>"
}

post_hostname () {
}

###
# rootpass
###
pre_rootpass () {
  sysconf=yes
}

display_rootpass () {
  if [ "$root_pass" = root ] ; then
    root_pass=
    echo "<meta active=pass1>"
  fi
  nls "Please now enter password for root (system administrator).<br>"
  nls "Single 'x' will appear regardless whatever you type. To delete<br>"
  nls "password press Del and/or Backspace, until 'x' disappears.<br><br>"
  echo "$(nls 'Password:') <input id=pass1 caption='$root_pass' pass=1><br>"
  echo "$(nls 'Re-enter:') <input id=pass2 caption='$root_pass' pass=1><br><br>"
  nls "If you have problems handling this password input boxes<br>"
  echo "<button res=1 caption='$(nls "_Enter passwords in visible text")'>"
}

# usage: get_input var_name default text...
check_pass () {
  if [ "$res" = 1 ] ; then
    get_input pass "$pass1" "$(nls "Please enter root password here:")"
    pass1="$pass"
    pass2="$pass"
  fi
  
  if [ "$pass1" = "" ] ; then
    info "$(nls "Password cannot be empty.")"
    return 1
  fi
  
  if [ "$pass1" != "$pass2" ] ; then
    info "$(nls "Passwords don't match.")"
    return 1
  fi
}

post_rootpass () {
  check_pass || return 1
  root_pass="$pass1"
}

###
# user
###
pre_user () {
  sysconf=yes
}

display_user () {
  nls "You can optionally add one regular user from here.<br>"
  nls "Of course, this can be also done using useradd command :^)<br>"
  nls "If you don't want to add any users here, simply leave<br>"
  nls "username blank.<br><br>"
  echo "$(nls "Username (login) :") <input id=user_name caption='$user_name'><br>"
  echo "$(nls "Realname (gecos) :") <input id=user_realname caption='$user_realname'><br>"
  echo "$(nls "Password for user:") <input id=pass1 caption='$user_pass' pass=1><br>"
  echo "$(nls "Re-enter password:") <input id=pass2 caption='$user_pass' pass=1><br><br>"
  nls "Realname might be left blank."
}

post_user () {
  if test "$user_name" ; then
    check_pass || return 1
    user_pass="$pass1"
  fi
}

###
# lang
###
select_timezone () {
Africa_zones=" Abidjan Accra Addis_Ababa Algiers Asmera Bamako Bangui Banjul Bissau Blantyre Brazzaville Bujumbura Cairo Casablanca Ceuta Conakry Dakar Dar_es_Salaam Djibouti Douala El_Aaiun Freetown Gaborone Harare Johannesburg Kampala Khartoum Kigali Kinshasa Lagos Libreville Lome Luanda Lubumbashi Lusaka Malabo Maputo Maseru Mbabane Mogadishu Monrovia Nairobi Ndjamena Niamey Nouakchott Ouagadougou Porto-Novo Sao_Tome Timbuktu Tripoli Tunis Windhoek"
America_zones=" Adak Anchorage Anguilla Antigua Araguaina Aruba Asuncion Atka Barbados Belem Belize Boa_Vista Bogota Boise Buenos_Aires Cambridge_Bay Cancun Caracas Catamarca Cayenne Cayman Chicago Chihuahua Cordoba Costa_Rica Cuiaba Curacao Dawson Dawson_Creek Denver Detroit Dominica Edmonton Eirunepe El_Salvador Ensenada Fort_Wayne Fortaleza Glace_Bay Godthab Goose_Bay Grand_Turk Grenada Guadeloupe Guatemala Guayaquil Guyana Halifax Havana Hermosillo Indiana/ Indianapolis Inuvik Iqaluit Jamaica Jujuy Juneau Kentucky/ Knox_IN La_Paz Lima Los_Angeles Louisville Maceio Managua Manaus Martinique Mazatlan Mendoza Menominee Merida Mexico_City Miquelon Monterrey Montevideo Montreal Montserrat Nassau New_York Nipigon Nome Noronha Panama Pangnirtung Paramaribo Phoenix Port-au-Prince Port_of_Spain Porto_Acre Porto_Velho Puerto_Rico Rainy_River Rankin_Inlet Recife Regina Rio_Branco Rosario Santiago Santo_Domingo Sao_Paulo Scoresbysund Shiprock St_Johns St_Kitts St_Lucia St_Thomas St_Vincent Swift_Current Tegucigalpa Thule Thunder_Bay Tijuana Tortola Vancouver Virgin Whitehorse Winnipeg Yakutat Yellowknife"
Antarctica_zones=" Casey Davis DumontDUrville Mawson McMurdo Palmer South_Pole Syowa Vostok"
Arctic_zones=" Longyearbyen"
Asia_zones=" Aden Almaty Amman Anadyr Aqtau Aqtobe Ashgabat Ashkhabad Baghdad Bahrain Baku Bangkok Beirut Bishkek Brunei Calcutta Chungking Colombo Dacca Damascus Dhaka Dili Dubai Dushanbe Gaza Harbin Hong_Kong Hovd Irkutsk Istanbul Jakarta Jayapura Jerusalem Kabul Kamchatka Karachi Kashgar Katmandu Krasnoyarsk Kuala_Lumpur Kuching Kuwait Macao Magadan Manila Muscat Nicosia Novosibirsk Omsk Phnom_Penh Pontianak Pyongyang Qatar Rangoon Riyadh Riyadh87 Riyadh88 Riyadh89 Saigon Samarkand Seoul Shanghai Singapore Taipei Tashkent Tbilisi Tehran Tel_Aviv Thimbu Thimphu Tokyo Ujung_Pandang Ulaanbaatar Ulan_Bator Urumqi Vientiane Vladivostok Yakutsk Yekaterinburg Yerevan"
Atlantic_zones=" Azores Bermuda Canary Cape_Verde Faeroe Jan_Mayen Madeira Reykjavik South_Georgia St_Helena Stanley"
Australia_zones=" ACT Adelaide Brisbane Broken_Hill Canberra Darwin Hobart LHI Lindeman Lord_Howe Melbourne NSW North Perth Queensland South Sydney Tasmania Victoria West Yancowinna"
Brazil_zones=" Acre DeNoronha East West"
Canada_zones=" Atlantic Central East-Saskatchewan Eastern Mountain Newfoundland Pacific Saskatchewan Yukon"
Chile_zones=" Continental EasterIsland"
Etc_zones=" GMT GMT+0 GMT+1 GMT+10 GMT+11 GMT+12 GMT+2 GMT+3 GMT+4 GMT+5 GMT+6 GMT+7 GMT+8 GMT+9 GMT-0 GMT-1 GMT-10 GMT-11 GMT-12 GMT-13 GMT-14 GMT-2 GMT-3 GMT-4 GMT-5 GMT-6 GMT-7 GMT-8 GMT-9 GMT0 Greenwich UCT UTC Universal Zulu"
Europe_zones=" Amsterdam Andorra Athens Belfast Belgrade Berlin Bratislava Brussels Bucharest Budapest Chisinau Copenhagen Dublin Gibraltar Helsinki Istanbul Kaliningrad Kiev Lisbon Ljubljana London Luxembourg Madrid Malta Minsk Monaco Moscow Nicosia Oslo Paris Prague Riga Rome Samara San_Marino Sarajevo Simferopol Skopje Sofia Stockholm Tallinn Tirane Tiraspol Uzhgorod Vaduz Vatican Vienna Vilnius Warsaw Zagreb Zaporozhye Zurich"
Indian_zones=" Antananarivo Chagos Christmas Cocos Comoro Kerguelen Mahe Maldives Mauritius Mayotte Reunion"
Mexico_zones=" BajaNorte BajaSur General"
Mideast_zones=" Riyadh87 Riyadh88 Riyadh89"
Pacific_zones=" Apia Auckland Chatham Easter Efate Enderbury Fakaofo Fiji Funafuti Galapagos Gambier Guadalcanal Guam Honolulu Johnston Kiritimati Kosrae Kwajalein Majuro Marquesas Midway Nauru Niue Norfolk Noumea Pago_Pago Palau Pitcairn Ponape Port_Moresby Rarotonga Saipan Samoa Tahiti Tarawa Tongatapu Truk Wake Wallis Yap"
SystemV_zones=" AST4 AST4ADT CST6 CST6CDT EST5 EST5EDT HST10 MST7 MST7MDT PST8 PST8PDT YST9 YST9YDT"
US_zones=" Alaska Aleutian Arizona Central East-Indiana Eastern Hawaii Indiana-Starke Michigan Mountain Pacific Samoa"
# this wouldn't work... (installer-sysconf issue)
#root_zones=" CET Cuba EET Egypt Eire Factory GB-Eire GB Greenwich GMT GMT+0 GMT-0 GMT0 Hongkong Iceland Iran Israel Jamaica Japan Libya MET PRC NZ NZ-CHAT Kwajalein Poland Portugal ROC ROK Singapore Turkey UCT MST CST6CDT EST EST5EDT HST MST7MDT Navajo PST8PDT W-SU WET Zulu UTC Universal"
zone_dirs=" Africa America Antarctica Arctic Asia Atlantic Australia Brazil Canada Chile Etc Europe Indian Mexico Mideast Pacific SystemV US"

  opened_zone=
  zone=$timezone

  case "$zone" in
    */* ) 
      opened_zone=$(echo $zone | sed -e 's|/.*||')
      ;;
  esac

  while : ; do
    dial <<EOF
<menu id=zone res=1 selected=$zone width=40 height=20>
$(
for f in $zone_dirs ; do
  echo "<item id=$f>$f/"
  if [ "$f" = "$opened_zone" ] ; then
    for e in `eval echo \\$${f}_zones` ; do
      echo "<item nohl=1 id=$f/$e>     $e"
    done
  fi
done
)
</menu>
$ok_cancel
EOF
    if [ "$res" = 2 ] ; then
      return 1
    fi
  
    case $zone in
      */* )
        timezone=$(echo $zone | sed -e 's|root/||')
        return 0
        ;;
      * )
        if [ "$opened_zone" = "$zone" ] ; then
          opened_zone=
        else
          opened_zone=$zone
        fi
        ;;
    esac
  done
}

###
# lang
###

pre_lang () {
  sysconf=yes
}

display_lang () {
  nls "Now you can set up language environment for your system.<br>"
  nls "Language is ISO language code, pl_PL for Polish, de_DE for German,<br>"
  nls "de_AT for German in .at, en_GB for British English and so on.<br><br>"
  
  echo "$(nls "Language :") <input id=lang caption='$lang'><br>"
  echo "$(nls "Timezone :") <input id=timezone caption='$timezone'> "
  echo "<button res=1 caption='$(nls "_Browse timezones")'><br><br>"
  
  utc=1
  if [ "$clock_utc" = no ] ; then
    utc=0
  fi

  echo -n "<check id=clock_utc checked=$utc> "
  
  nls "My hardware clock runs UTC.<br>"
  nls "Hardware clock running UTC is normal on Unix boxes, however Windows<br>"
  nls "can't get it, so if you are using Windows better uncheck this."
}

post_lang () {
  if test "$res" = 1 ; then
    select_timezone
    return 1
  fi
}


###
# boot
###
pre_boot () {
  # Autogenerate config. We only do so for FAT paritions with boot flag.
  # Users who have more the one linux or BSD on their hard drive, are expected
  # to be wise enough to create config on their own.
  load_parted
  load_config
  
  if [ "$boot_loader_other" = "" ] ; then
    boot_loader_other=" "
    for f in $dest_devices ; do
      for id in $(parted -s $f print | \
    	          grep '^[1-9].*FAT.*boot' | \
	          sed -e 's/^\([1-9][0-9]*\).*/\1/') ; do
        boot_loader_other="$boot_loader_other dos:dos-`basename $f`$id:$f$id"
      done
    done
  fi

  sysconf=
  save_config
}

display_boot () {
  some=
  nls "Current ,,other'' OS configuration:<br><br>"
  for img in $boot_loader_other ; do
    some=1
    eval $(parse_boot_loader_entry $img)
    nls "%s is %s with root = %s<br>" "$img_label" "$img_os" "$img_root"
    if [ "$img_kernel" != "" ] ; then
      nls "      kernel = %s, initrd = %s<br>" "$img_kernel" "$img_initrd"
    fi
  done
  echo "<br>"
  nls "If you are happy with it, just press [ Next >> ],<br>"
  nls "otherwise "
  echo "<button caption='$(nls "_Configure bootloader")' res=1>."
}

post_boot () {
  case "$res" in
    1 )
      ui-boot -P $pkgsfile -C $conffile -G $groupsfile
      load_config
      res=1002
      ;;
  esac
}

###
# bootdev
###
pre_bootdev () {
}

display_bootdev () {
  nls "Bootloader can be installed in several places.<br>"
  nls "The most common choice is to install it on first hard disk's<br>"
  nls "Master Boot Record (MBR). This is reflected by /dev/hda or<br>"
  nls "/dev/sda choice below (for IDE or SCSI respectively).<br><br>"
  nls "However it is also possible to install bootloader at the<br>"
  nls "beginning of hard disk partition and chain-load it later,<br>"
  nls "from other bootloader.<br><br>"
  nls "A choice of 'auto' means to install bootloader on MBR of disk<br>"
  nls "that contains /boot (or / if there is no /boot) partition.<br><br>"
  nls "In the most common case of single IDE drive, leave it<br>"
  nls "with 'auto'.<br><br>"
  nls "Bootloader device: "
cat <<EOF
<menu id=bld hidden=1>
<item id=auto>$(nls Automatic)
<item id=/dev/hda>$(nls "First IDE drive")
<item id=/dev/sda>$(nls "First SCSI drive")
<item id=/dev/hda1>$(nls "First partition on 1st IDE drive")
</menu>
<input id=boot_loader_device label='$(nls "_Examples")' 
caption='$boot_loader_device' menu=bld>
EOF
}

post_bootdev () {
}

###
# run
###
pre_run () {
}

display_run () {
  nls "Ok, you have setup your PLD Linux installation.<br><br>"
  nls "Now I will run batch installer. This will take a while...<br>"
}

post_run () {
  if [ "$res" = 1002 ] ; then
    nls "Running installer...\n"
    if [ $real_system = no ] ; then
      installer
    else
      true
    fi
    if [ $? != 0 ] ; then
      wait_key
      info $(nls "As installer failed to do its job,<br>you need to change the configuration.<br><br>Use [ << Back ] button to get back,<br>and change parameters.<br>")
      return 1
    else
      nls "Installation finished.\n"
      nls "Press the [Enter] key.\n"
      read JUNK
    fi
  fi
}

###
# fini
###
pre_fini () {
}

display_fini () {
  nls "Congratulations, you have successfully installed PLD Linux.<br><br>"
  nls "Please remove all installation media (floppies, cdroms).<br><br>"
  nls "Now, if you press [ Reboot ], system will reboot. If you don't<br>"
  nls "want it to reboot (just to get back to main menu), press<br>"
  nls "[ Cancel ]."
}

    
post_fini () {
}


##################
# Main loop
##################

going_back=

# main loop
while true ; do
  if eval pre_$step ; then
    dial <<EOF
<meta title="$(nls "The Sorcerer: step %d [%s]" "$(step_no)" "$step")">
<meta active=next>
<br>
$(display_$step)
<br><br>
                            $(
if [ "$(prev_step)" = "" ] ; then
  echo "            "
fi
echo "<button id=cancel caption=\"$(nls '_Cancel')\" res=1000> "
if [ "$(prev_step)" != "" ] ; then
  echo "<button id=back caption=\"$(nls '_<_< Back')\" res=1001> "
fi
if [ "$(next_step)" != "" ] ; then
  echo "<button id=next caption=\"$(nls 'Next _>_>')\" res=1002>"
else
  echo "<button id=next caption=\"$(nls 'Reboot')\" res=1003>"
fi
)
EOF
  else
    # we were told to skip this step
    if test "$going_back" ; then
      res=1001
    else
      res=1002
    fi
  fi
  
  eval post_$step || continue

  if test "$sysconf" ; then
    ( save_sys_config )
  else
    ( save_config )
  fi
  
  case "$res" in
  1000 )
    if yes_no yes "$(nls "Are you sure to leave The Sorcerer?")" ; then
      exit 0
    fi
    ;;
  1001 )
    step=$(prev_step)
    going_back=yes
    if test -z "$step" ; then
      step=prep
    fi
    ;;
  1002 )
    step=$(next_step)
    going_back=
    ;;
  1003 )
    break
    ;;
  esac
done

echo
echo "$(nls "Have a nice penguin.")"
echo

if [ $real_system = no ] ; then
  reboot
fi

exit 0

# vim:ft=sh
