#!/bin/bash

# TODO: give all those functions an unique prefix

# a submenu for Disk structure
# Partitioning
# mounting - RAID

# ---------------- main menu ----------------------

function disk_structure_screen() {
  # do things here to display the menu items for setting up disks

  if check_dependency install_start ;then
    # Whoops! We already have stuff starting to install
    confirm "WARNING! Data is already being installed to the
partition structure you have set up. Very bad things
happen when you mount new partitions on top of them.
It is *highly* recommended that you choose
\"restart installer\" from the main menu if you have to
repartition, and start from scratch.
continue?" --defaultno ||
    return 1
  fi

  local ICOMMAND="A" # always default to previous selection
  local DONE=false
  while ! $DONE ;do

    local TEXT="Please create at least a root partition.
There currently is a bug with grub on xfs, so
you can't install grub to an xfs / without a seperate
non-xfs /boot partition."
    ICOMMAND=`run_dialog              \
      --ok-label "Select"             \
      --title  "Disk structure menu"  \
      --default-item  $ICOMMAND       \
      --item-help                     \
      --menu "$TEXT"                  \
      0 0 0                         \
      "A" "[*]Partition Disks"   "Create partitions on your drives" \
      "B" "[*]Make MD RAID Devices" "Create RAID devices using mdadm"    \
      "C" "Format/mount filesystems and swap" "Format and mount your partitions" \
      "D" "Done"        "We're all done here, let's get on with it" ` ||
    return 1 #return with a failure if canceled


    case $ICOMMAND in
      A)
        fdisc_menu # do the partitioning
      ;; # maybe partitions are already created
      B)
        create_md_device # Make ourselves some MD devices!
      ;;
      C)
        while mount_menu ;do true ;done # do the mounting until user quits
      ;;
      D)
        if need_dependency disk-root; then
          rm -f $FINALFILES/etc/fstab
          cat $TEMPLATE_DIR/fstab.first /tmp/fstab $TEMPLATE_DIR/fstab.last \
            >$FINALFILES/etc/fstab
          fill_dependency disk
          DONE=true
        fi
      ;;
    esac
  done

#check for swap partition!
  if ! check_dependency disk-swap; then
    if confirm "Do you want to make a swapfile? (swap == virtual memory)
You have no dedicated swap partition."; then
      mk_swap_file
    fi
  fi

  return 0 # When we've reached this point, always return success.

}

# ------------ partitioning part --------------------------

list_discs()  {

  # sfdisk reads /proc/partitions for discs so it is the same as cat
  # /proc/partitions but better output

  # however, sfdisk -s outputs an error messages on ppc about
  # unrecognized msdos partitions. we ignore it with 2>/dev/null

  # TODO: sanitize devfs partition names

  local DISK

  sfdisk -s 2>/dev/null | grep '^/dev' | cut -d : -f1 |
  while read DISK; do #WARNING: This is a subshell.
  # a cdrom has no geometry allowing us to remove it from the list
    if ! sfdisk -qg "${DISK}" | grep -q "cannot get geometry"; then
      echo  "${DISK}"
      echo  "Size $( sfdisk -sq "${DISK}" )"
    fi
  done

}

select_disc()  {

  local -a LIST_DISCS
  explode "$(list_discs)" $'\n' "LIST_DISCS"

  local DISC

  debug_log "diskStructure" 3 "Disk list:" "${LIST_DISCS[@]}"

  if [[ ${#LIST_DISCS[@]} == 0 ]] ;then
    display_message "No discs could be found.
You may need to load more modules (shell out, use modprobe)"
    return 1
  fi

  run_dialog \
    --title "Disk Selection Menu"                                     \
    --menu  "Please select a disk to partition. Sizes are in blocks." \
    0 0 0                                                            \
    "${LIST_DISCS[@]}" # 2 entries per disk - name and size

}

fdisc_menu()  {

  local DISC PROG
  DISC=`select_disc` &&
  if [ "$ARCH" = "ppc" ]; then
    display_message "Remember you need to create a bootstrap partition first
(type 'b' at the prompt)."
    debug_log "diskStructure" 2 "Running mac-fdisk on $DISC"
    mac-fdisk "$DISC"
  else
    PROG=`memory_menu "fdisc_tool" "Partitioning Menu" ""             \
      "Please choose the program for partitioning $DISC" "cfdisk"     \
      "cfdisk" "Menu-driven partitioning program. Easy to use."       \
      "fdisk"  "Text-based. A little harder to use, more features"    \
      "parted" "Text-based. Many features, such as moving partitions" ` &&

    debug_log "diskStructure" 2 "Running $PROG on $DISC"
    try_run -nc ${PROG} "${DISC}"
  fi
}

# --------------------- NEW RAID STUFF ----------------------

dsr_show_warning() {
  run_dialog --title "WARNING!" \
    --msgbox "If you plan on mounting the device you're about to create as
/ (the root), you need to ensure that you make the
partition types \"Linux raid autodetect\" (ID 0xFD).
Otherwise your system will not boot!" 0 0
}

dsr_device_name() {
  run_dialog --title "Multiple Disk Device Name" \
  --inputbox "Enter the fully qualified device name (ex /dev/md0)" 0 0 \
  "/dev/md0"
}

dsr_raid_level_menu() {
  memory_menu "raidlevel" "Select RAID level" ""         \
    "Select a RAID level" "1"                            \
    "0" "Striping"                                       \
    "1" "Mirroring"                                      \
    "4" "Independent Data disks with shared Parity disk" \
    "5" "Independent data disks with distributed parity" \
    "6" "Independent data disks with dual distributed parity"
#    "3" "Parallel transfer with parity" off \
#    "2" "Hamming code ECC" off \
}

dsr_choose_partitions() {
  LIST_PARTS=()
  # Use sed to append an "off" line to every entry
  explode "$(list_parts | sed 's/^\(Size: .*\)$/\1\noff/')" $'\n' \
    LIST_PARTS

  if [[ ${#LIST_PARTS[@]} == 0 ]] ;then
    display_message "No partitions could be found. In order to avoid
warnings about broken partition tables on bootup,
it is recommended that you partition even the drives
that you want to use in a RAID as a whole (into one
big partition).
You may need to load more modules (shell out, use modprobe)
or partition your disks."
    return 1
  fi


  run_dialog --title "Select partitons to create a RAID device from" \
  --separate-output                                                  \
  --checklist "Mark partitions to be made into the RAID array" 0 0 0 \
  "${LIST_PARTS[@]}" |
    sed 's:^[[:space:]]*:/dev/:g'
  # If anyone knows how that whitespace creeps in there, I owe him a beer (Bear)
}

# Arguments:
# $1: name of md device to create
# $2: raid level
# $3: newline-seperated list of devices
# $4: count of selected partitions
dsr_sanity_check() {
  local ERROR_FILE=/tmp/raid-errors.$$
  rm -f $ERROR_FILE

  debug_log "diskStructure" 2 "Checking RAID settings: DEVICE=$1, LEVEL=$2"
  debug_log "diskStructure" 2 "Generating from $4 partitions: $3"

  #verify raid level device count
  local COUNT_CHECK=0
  case $2 in
    0|1) COUNT_CHECK=2
    ;;
    2|3|4|5) COUNT_CHECK=3
    ;;
    6) COUNT_CHECK=4
    ;;
  esac

  #ensure they entered a device!
  if [ "$1" = "" ] ; then
    echo "You must specify a device to create!" >>$ERROR_FILE
  fi

  if [ $4 -lt $COUNT_CHECK ] ; then
    echo "RAID level $2 must have at least $COUNT_CHECK devices" \
      >>$ERROR_FILE
  fi

  #verify selected devices are block devices
  local DEVICES
  for DEVICES in $1 $3 ; do
    if [ ! -b "$DEVICES" ] ; then
      echo "$DEVICES is not a block device!" >>$ERROR_FILE
    fi
  done

  if [ -e $ERROR_FILE ] ;then
    run_dialog --title "Failed to create MD device" --textbox \
      $ERROR_FILE 0 0
    return 1
  fi
}

dsr_make_raid_config() {
  #generate the mdadm.conf
  echo 'DEVICE /dev/hd*[0-9] /dev/sd*[0-9]' > $FINALFILES/etc/mdadm.conf
  mdadm --detail --scan >> $FINALFILES/etc/mdadm.conf
  mdadm --detail --scan -v >/tmp/md-devices
  # Store devices used for partition selection
}

create_md_device() {
  local DEVICE_NAME LEVEL PARTS P_COUNT
  dsr_show_warning                      &&
  DEVICE_NAME=`dsr_device_name`   &&
  LEVEL=`dsr_raid_level_menu`     &&
  PARTS="`dsr_choose_partitions`" &&
  P_COUNT=`echo $PARTS | wc -w`   &&

  dsr_sanity_check "$DEVICE_NAME" "$LEVEL" "$PARTS" "$P_COUNT" &&
  try_run mdadm --create $DEVICE_NAME --level=$LEVEL --raid-devices=$P_COUNT $PARTS &&
  dsr_make_raid_config                          &&
  debug_log "diskStructure" 1 "Successfully generated $DEVICE_NAME." &&
  si_queue mdadm
}

# ---------------- formatting and mounting ------------------

mnt_get_part_type() {
  if [[ $1 == md* ]] ;then
    echo -n "RAID "
    mdadm --detail --brief /dev/$1 |
      sed 's/^.*\(level.*\)UUID.*$/\1/'
  else
    if [[ $ARCH == "ppc" ]] ;then
      mac-fdisk -l | grep "^/dev/$1[[:space:]]" |
        sed 's/^.*  //'
    else
      sfdisk -lq 2>/dev/null | # Bug in sfdisk makes it not honor -q
        grep "^/dev/$1[[:space:]]" | sed 's/^.*  //'
    fi
  fi
}

list_parts()  {
  local PARTITION SIZE
  touch /tmp/fstab
  touch /tmp/md-devices
  # grepping a non-existant file gives an error
  cat /proc/partitions | awk '$3 !~ /^1$/ {print $4 " " $3}' | grep -v ram |
    grep -v disc | grep -v name | grep '^[^ ]*[0-9]' |
    while read PARTITION SIZE ;do #SUBSHELL!
      if [[ -n "$PARTITION" ]] && ! grep -q "^/dev/$PARTITION	" /tmp/fstab &&
        ! grep -q "devices=\([^,]*,\)*/dev/$PARTITION\(,\|$\)" /tmp/md-devices
      then # don't do nil strings, partitions we mounted already, RAID parts
        echo "$PARTITION"
        echo "Size: $(( SIZE / 1024 ))MB Type: \
$(mnt_get_part_type $PARTITION | tr '\n' ' ')"
        # Be very paranoid about getting exactly one line out of this
      fi
    done
}

get_part()  {

  LIST_PARTS=()
  explode "$(list_parts)" $'\n' LIST_PARTS

  debug_log "diskStructure" 3 "Partition list:" "${LIST_PARTS[@]}"

  if [[ ${#LIST_PARTS[@]} == 0 ]] ;then
    display_message "No partitions could be found. Either all are
already mounted, or none are available.
You may need to load more modules (shell out, use modprobe)
or partition your disks."
    return 1
  fi

  run_dialog                               \
    --title "Partition Selection Menu"     \
    --cancel-label "Done"                  \
    --menu  "Select a partition to mount." \
    0 0 0                                  \
    "${LIST_PARTS[@]}"

}

get_filesystem()  {

  memory_menu "filesystem" "Filesystem Selection Menu" ""  \
    "Please select what filesystem to use for $1" "ext2"   \
    "ext2"      "Second Extended file system"              \
    "ext3"      "Second Extended journaling file system"   \
    "reiserfs"  "Reiserfs journaling file system"          \
    "xfs"       "XFS journaling file system"               \
    "jfs"       "JFS journaling file system"               \
    "swap"      "Swap partition"

}

get_mount_point()  {

  if ! check_dependency disk-root  ;then
    display_message "Automatically choosing / as first mount point"
    echo "/"
  elif  [  "$2"  ==  "swap"  ];  then
    echo "none"
  else
    local -a MOUNT_POINTS
    MOUNT_POINTS=(
    # Mark for how long texts can get:                         over here v"
    "/boot"  "Put boot-relevant stuff somewhere special for old BIOS'es"
    "/home"  "Give users their own partition so they can't fill / up"
    "/root"  "For the paranoid: extra HD space for recovery when / is full"
    "/usr"   "Used to seperate system programs from the bulk of the data"
"/usr/share" "No idea what this is for. Tell BearPerson on IRC :-)"
    "/var"   "Guarantees that logs or source caches can't fill /"
    "other"  "own custom mount point (forbidden: /etc, /bin, /sbin, /lib)" )

    # Filter already-mounted partitions
    local partnum=$(( ${#MOUNT_POINTS[@]} / 2 ))
    local i
    for((i=0;i<partnum;i++)) ;do
      # literal tabs:
      if grep -q "	${MOUNT_POINTS[2*i]}	" /tmp/fstab ;then
        unset MOUNT_POINTS[2*i] MOUNT_POINTS[2*i+1]
        # Luckily, this doesn't move the other entries down
      fi
    done

    local MPOINT
    MPOINT=$(run_dialog --title "Mount point selection"    \
      --menu  "Please select where to mount $1 (type $2)"  \
      0 0 0                                               \
      "${MOUNT_POINTS[@]}") &&
    if [[ "$MPOINT" == "other" ]] ;then
      inputbox  "Please choose where to mount $1 (type $2)"  "/"
    else
      echo "$MPOINT"
    fi
  fi
}

get_mkfs_cmd() {
  if $3 ;then # check for errors
    case $1 in
          ext2)  echo  "mke2fs -c $2"    ;;
          ext3)  echo  "mke2fs -c -j $2" ;;
      reiserfs)  echo  "badblocks -o /tmp/badblocks $2 ; mkreiserfs -B /tmp/badblocks $2"   ;;
           xfs)  echo  "mkfs.xfs -f $2"     ;; # no badblocks handling
           jfs)  echo  "mkfs.jfs -c $2"     ;;
          swap)  echo  "mkswap -c $2"    ;;
             *)  false                ;;
    esac
  else
    case $1 in
          ext2)  echo  "mke2fs $2"     ;;
          ext3)  echo  "mke2fs -j $2"  ;;
      reiserfs)  echo  "mkreiserfs $2" ;;
           xfs)  echo  "mkfs.xfs -f $2"   ;; #ignore existing partition
           jfs)  echo  "mkfs.jfs $2"   ;;
          swap)  echo  "mkswap $2"     ;;
             *)  false                 ;;
    esac
  fi
}

# Returns the spell needed to provide support for given fs
get_fs_spell() {
  case $1 in
# e2fsprogs is installed anyway, it includes fsck
    reiserfs)  echo "reiserfsprogs" ;;
         xfs)  echo "xfsprogs"      ;;
         jfs)  echo "jfsutils"      ;;
  esac
}

get_mount_opts()  {

  case  $1  in
    reiserfs)  echo "defaults,notail,noatime"  ;;
        swap)  echo "defaults"                 ;;
           *)  echo "defaults,noatime"         ;;
  esac
}

mount_fsys()  {

  local MPOINT="${TARGET}$3"
  case  $2  in
    swap)
          #TODO: would anyone ever not want swap turned on during install?
          swapon "$1"               &&
          fill_dependency disk-swap $1 ||
          echo "Activating swap failed. This is non-fatal. Continuing anyway."
          true
    ;;
       *)
          mkdir -p $MPOINT                                               &&
          try_run -e "Mointing $1 as $2 to $MPOINT failed." \
            mount -t $2 -o "$4" "$1" "$MPOINT"                           &&
          case  $3  in
                /)
                   fill_dependency disk-root $1
                ;;
            /boot)
                   fill_dependency disk-boot $1
                ;;
                *) true      ;;
          esac                                                           &&
          debug_log "diskStructure" 1 "Nicely mounted $1 as $2 to $MPOINT" ||
          {
            return 1
          }
    ;;
  esac
}

get_fstab_opts()  {

  case $2 in
    /)  echo "$(get_mount_opts $1)	0 1"  ;;
    *)  echo "$(get_mount_opts $1)	0 2"  ;;
  esac

}

make_fstab_line()  {
  # TODO: this is a hack
  echo "$1	$3	$2	$4"
}

mount_menu()  {
  if ! check_dependency disk-root  ;then
    display_message "Please first mount the partition that will be /
then mount \"up the tree\" (/usr before /usr/share)"
  fi

# TODO: make this code look nicer at least... maybe add some ribbons

  local CHECK PART FSYS MPOINT MKFSCMD QUESTION MNT_OPTS FSTAB_OPTS

   CHECK=false
    PART=/dev/`get_part`               &&
    FSYS=`get_filesystem   $PART`      &&
  MPOINT=`get_mount_point $PART $FSYS` &&
  if confirm "Do you want to check $PART for errors?" --defaultno ;then
    CHECK=true
  fi                                         &&
  if confirm "Do you want to format $PART?" ;then
    MKFSCMD=`get_mkfs_cmd $FSYS $PART $CHECK`      &&
    QUESTION="This is the command to create the filesystem,
as far as I can figure it out.
If you want to change anything, you can now.
If you don't know what to do, just hit OK."        &&
    MKFSCMD=$( inputbox "$QUESTION" "${MKFSCMD}" ) &&
    if [[ $FSYS == jfs ]] ;then # mkfs.jfs doesn't line-buffer its output
      eval "try_run -nc $MKFSCMD"
    else
      eval "try_run $MKFSCMD"
    fi                                             ||
    return 1
  elif $CHECK ;then
    badblocks $PART
  fi                                              &&
    MNT_OPTS=`get_mount_opts $FSYS $MPOINT` &&
  mount_fsys $PART $FSYS $MPOINT "$MNT_OPTS"      &&
  FSTAB_OPTS=`get_fstab_opts $FSYS $MPOINT` &&
  make_fstab_line $PART $FSYS $MPOINT "$FSTAB_OPTS" >>/tmp/fstab &&
  si_queue $( get_fs_spell $FSYS )
  # And this spell should not get installed before disks are done and basic
  # stuff is there
}

mk_swap_file()  {

  local DEVICE SWAPFILE SIZE
  DEVICE=`inputbox "Where should the swapfile go?" "/.swapfile"` &&
  SWAPFILE="$TARGET$DEVICE"                                      &&
  SIZE=`inputbox "How big do you want it to be? (in MB)" "1024"` &&

  if confirm "Okay. Swapfile at $DEVICE, size $SIZE. That right, boss?" ;then
    dd  if=/dev/zero of=$SWAPFILE bs=1M count=$SIZE &&
    try_run mkswap      $SWAPFILE                   &&
    chmod  000          $SWAPFILE                   &&
    try_run swapon      $SWAPFILE                   &&
    make_fstab_line $DEVICE "swap" "swap" "defaults\t0 2" >>/tmp/fstab &&
    fill_dependency disk-swap file||
    press_enter "diskStructure" 0
  fi
}
