#!/bin/bash 

# Note: In this file, we use dependencies to carry information
# as a more elegant alternative to global variables.
# But we also have to carry variables into run_template.
# Fortunately, a local variable in bash is accessible in all
# function we call from that function. Not quite elegant, but it works.

#bootloader stuff
function bootloader_screen() {
  need_dependency disk          &&
  need_dependency install_start &&
  need_dependency linux         &&
  si_wait linux                 &&
  config_bootloader
}

# usage: create_etc_mtab

# this functions creates a valid $TARGET/etc/mtab file that will make
# df work in a chroot. This is usefull for yabootconfig, lilo and
# grub-install for instance, if they are run in chroot.

create_etc_mtab() {

  # replace $TARGET followed by zero or more /, by /

  cat /proc/mounts | grep " ${TARGET}" |
  sed -e "s:${TARGET}/*:/:g" > "${TARGET}/etc/mtab"

}

bl_choose_loader() {
# TODO: Auto-generate this
  if [ "$ARCH" == "ppc" ] ;then
    echo "yaboot" # We don't have any choice, why bother do display a menu?
  else
    memory_menu bootloader "Bootloader selection menu" "--item-help"           \
      "Please select the bootloader you wish to use to boot your SMGL system"  \
      "lilo"                                                                   \
      "lilo" "The LInux LOader"                                                \
  "lilo has been the standard-issue bootloader for many people for quite long" \
      "grub" "GNU GRUB Multiboot boot loader"                                  \
  "GRUB is a dynamic, interactive bootloader - liked by some, hated by others"
  fi #TODO: make these more neutral
}

bl_choose_target() {
  local QUESTION
  if check_dependency disk-boot ;then # we have a seperate /boot partition
    QUESTION="Do You want to install the boot loader to the
Master Boot Record of the disk that /boot is on
or to the Boot Record of the /boot partition?"
    if run_dialog --yes-label "MBR" --no-label "Partition" \
               --yesno "$QUESTION" 0 0 ;then
      get_dependency disk-boot |
        sed -e 's/part[0-9]*$/disc/' -e 's/[0-9]*$//'
      # partX -> disc conversion for devfs, hdaX -> hda otherwise
    else
      get_dependency disk-boot
    fi # this is the command that outputs the target to 
  else
    QUESTION="Do You want to install the boot loader to the
Master Boot Record of the disk that / is on
or to the Boot Record of the / partition?"
    if run_dialog --yes-label "MBR" --no-label "Partition" \
               --yesno "$QUESTION" 0 0 ;then
      get_dependency disk-root |
        sed -e 's/part[0-9]*$/disc/' -e 's/[0-9]*$//'
      # partX -> disc conversion for devfs, hdaX -> hda otherwise
    else
      get_dependency disk-root
    fi
  fi
}

config_bootloader() {

  local BOOTLOADER TARGET_DEV # The device to install the loader to
  BOOTLOADER=`bl_choose_loader`  &&

  # there is no MBR choice on ppc machines

  if [ "${ARCH}" == "ppc" ]; then
    TARGET_DEV=""
  else
    TARGET_DEV=$(bl_choose_target)
  fi                                   &&

  si_wait $BOOTLOADER                  &&

  bl_${BOOTLOADER}_config $TARGET_DEV  &&
  bl_${BOOTLOADER}_install $TARGET_DEV &&

  fill_dependency bootloader $BOOTLOADER

}

# -----------------GRUB-------------------------
bl_grub_config() {

  mkdir -p "${TARGET}/boot/grub"

# Variables needed for the grub template:
  local BL_BOOTLOC
  local BL_KVERSION
  local BL_ROOTDEV


# Okay, let's try to find how grub calls the /boot partition.
# Add a file that will very likely be uniquely there, and let grub search for it
  local GRUB_DUMMY_FILE="grub.$RANDOM.findfile"
  touch ${TARGET}/boot/$GRUB_DUMMY_FILE    &&
  # special thanks to the grub spell for some ideas boldly stolen here
  if check_dependency disk-boot ;then # seperate part for /boot
    BL_BOOTLOC="$( echo "find /${GRUB_DUMMY_FILE}" |
      chroot_cmd grub --no-floppy --batch |
      grep -A 1 "^grub>" | head -n 2 | tail -n 1)"
  else
    BL_BOOTLOC="$( echo "find /boot/${GRUB_DUMMY_FILE}" |
      chroot_cmd grub --no-floppy --batch |
      grep -A 1 "^grub>" | head -n 2 | tail -n 1)/boot"
  fi                                       &&
  rm -f ${TARGET}/boot/$GRUB_DUMMY_FILE    &&

  BL_KVERSION=$KERNEL_VERSION           &&

  BL_ROOTDEV=$( get_dependency disk-root ) &&

  run_template $TEMPLATE_DIR/grub.conf $TEMPLATE_DIR/bootloader.patterns \
    >${TARGET}/boot/grub/menu.lst          &&

  if confirm "Do you want to edit /boot/grub/menu.lst?" --defaultno ;then
    ${EDITOR:-nano} "${TARGET}/boot/grub/menu.lst"
  fi
}

bl_grub_install() {

  # get boot record

  # install grub (it is a shell script using df, and thus /etc/mtab to
  # locate file)

  create_etc_mtab &&
  try_run -e "installing grub" chroot_cmd grub-install --no-floppy "$1"

  debug_enter "bootloader" 2

}

#-------------LILO----------------------

bl_lilo_config() {

  # this one is easy
  local BL_KVERSION
  local BL_ROOTDEV
  local BL_TARGET

  BL_KVERSION=$KERNEL_VERSION                    &&

  BL_ROOTDEV=$(get_dependency disk-root)         &&

  BL_TARGET=$1 &&

  # copy boot.bmp
  cp -a /boot/boot.bmp "${TARGET}/boot/boot.bmp" &&

  # create a configuration file
  mkdir -p "${TARGET}/etc"                       &&
  run_template $TEMPLATE_DIR/lilo.conf $TEMPLATE_DIR/bootloader.patterns \
    >${TARGET}/etc/lilo.conf                     &&

  if confirm "Do you want to edit /etc/lilo.conf?" --defaultno ;then
    ${EDITOR:-nano} "${TARGET}/etc/lilo.conf"
  fi

}

bl_lilo_install() {

  try_run -e "installing lilo" chroot_cmd lilo -v

  debug_enter "bootloader" 2

}

#-----------YABOOT-------------------
# TODO: Have someone who knows yaboot look over this

bl_yaboot_config() {

  # yaboot workarounds
  # It also wants /etc/fstab to exist for whatever reason
  cp $FINALFILES/etc/fstab $TARGET/etc/fstab
  # Its tools expect sysfs somewhere, mount it
  mkdir $TARGET/sys
  mount sysfs -t sysfs $TARGET/sys
  # yabootconfig uses df, which needs /etc/mtab
  create_etc_mtab
  # hfsutils are required to install yaboot
  si_wait hfsutils

  local BL_BOOTLOC
  local BL_KVERSION

  yabootconfig -t "${TARGET}" --noinstall -q                ||
  {
    echo "Yabootconfig failed to run ($?). This is a semi-known problem."
    echo "If this still occurs, please report it to BearPerson on IRC"
    press_enter
  } >&2

  # remove the default image section written by yabootconfig
  # which are the last 3 lines of /etc/yaboot.conf

  head -n -3 "${TARGET}/etc/yaboot.conf" > /tmp/yaboot.conf &&
  cp /tmp/yaboot.conf "${TARGET}/etc/yaboot.conf"           &&

# TODO: Check if this needs fixed up like grub
  if check_dependency disk-boot; then
    BL_BOOTLOC=""
  else
    BL_BOOTLOC="/boot"
  fi                                                        &&

  BL_KVERSION=$KERNEL_VERSION                               &&

  # _append_ our own image section

  run_template $TEMPLATE_DIR/yaboot.conf.last $TEMPLATE_DIR/bootloader.patterns \
    >>${TARGET}/etc/yaboot.conf                             &&

  if confirm "Do you want to edit /etc/yaboot.conf?" --defaultno ;then
    ${EDITOR:-nano} "${TARGET}/etc/yaboot.conf"
  fi
}

bl_yaboot_install() {

  # we use --nonvram since we don't have nvsetenv installed

  try_run -e "installing yaboot" chroot_cmd ybin --nonvram

  debug_enter "bootloader" 2

}
