#!/bin/bash

# postinst operations for installation on a "new" partition, i.e., full grub
# setup needed, etc.

if [ `whoami` != 'root' ] ; then
  echo "This script must be run with root privileges."
  exit 1
fi

# source in the functions
source /opt/vyatta/sbin/install-functions

# the INSTALL_LOG env var should be exported by the "caller".
# it will be used to log messages.

# the base install drive e.g. sda
INSTALL_DRIVE=$1
# the install partition e.g. sda1
ROOT_PARTITION=$2
# install type: "union" or "old"
INSTALL_TYPE=$3

# Default user
DEFAULT_USER=vyos

# copy configuration to the config directory
copy_config () {
  local cfg_dir=${INST_ROOT}${VYATTA_CFG_DIR}

  # create the config directory
  mkdir -p $cfg_dir
  chgrp vyattacfg $cfg_dir
  chmod 775 $cfg_dir

  # create our config partition marker
  touch $cfg_dir/.vyatta_config

  if [ -d /mnt/config ]; then
    echo "Copying old configurations to config partition."
    cp -a /mnt/config/* $cfg_dir/ >&/dev/null
  else
    # Find the config files and give the user the option to copy config files
    # TODO: this needs cleaned up

    # First candidate: The config file on the running system.  Note
    # that this will include any changes made and saved by the user,
    # as well as changes such as interface MAC addresses automatically
    # generated by the user.  So it is the first choice.
    if [ -f "${VYATTA_CFG_DIR}/config.boot" ]; then
      config=${VYATTA_CFG_DIR}/config.boot
    fi

    # Third candidate: The default config file
    DEF_CONF=$vyatta_sysconfdir/config.boot.default
    if [ -f $DEF_CONF ]; then
	config="$config $DEF_CONF"
    fi

    if [ -n "$config" ]; then
      echo "I found the following configuration files:"
      for file in $config; do
        echo "    $file"
      done

      default=$(echo -e $config | awk '{ print $1 }')

      while [ -z "$configfile" ]; do
        echo -n "Which one should I copy to $INSTALL_DRIVE? [$default]: "
        configfile=$(get_response "$default" "$config")
      done
      
      echo
      echo "Copying $configfile to $INSTALL_DRIVE."
      cp -p $configfile $cfg_dir/config.boot >&/dev/null
      if [ $? != 0 ]; then
        lecho "Error copying file $configfile to config directory. Exiting..."
        exit 1
      fi
    fi
  fi

  # set the permissions on the new config file
  if [ -f "$cfg_dir/config.boot" ]; then
    chgrp vyattacfg $cfg_dir/config.boot
    chmod 775 $cfg_dir/config.boot
  fi

  # copy ssh keys
  if [ -d /mnt/ssh ]; then
	echo "Copying SSH keys."
	cp -p /mnt/ssh/* ${INST_ROOT}/etc/ssh
  fi
}

# setup grub on the boot sector of a user selected drive
install_grub () {
  grub_inst_drv=''
  raid_slaves=''
  
  if [ ${INSTALL_DRIVE:0:2} == "md" ]; then
    raid_slaves=`ls /sys/block/${INSTALL_DRIVE}/slaves`
    grub_inst_drv="md raid"
  fi

  mkdir -p $grub_root/boot/grub

  # Let the user choose the boot sector
  while [ -z "$grub_inst_drv" ]
  do
    echo "I need to install the GRUB boot loader."
    echo "I found the following drives on your system:"
    select_drive "Which drive should GRUB modify the boot partition on?" \
      'grub_inst_drv'
  done

  echo -n "Setting up grub:  "
  lecho "Setting up grub..."

  # Install grub in the boot sector of the primary drive, or if the installation
  # target is a raid setup, then install it into the boot sector of all slave
  # members.
  
  progress_indicator start

 if [ -f "/tmp/efiparts.tmp" ]; then
     mkdir -p $grub_root/boot/efi
     readarray parts < /tmp/efiparts.tmp
     part_length=${#parts[@]}
     bootloader_name="VyOS"
     I=0
     for part in "${parts[@]}"
     do
	#Name the bootloaders something different if we have a RAID
         if [ "$part_length" -gt "1" ]; then
             bootloader_name="VyOS (RAID disk $I)"
             ((I++))
         fi
         mkdosfs -F 32 -s 1 -n EFI /dev/$part >&/dev/null
         mount /dev/$part $grub_root/boot/efi
         output=$(grub-install --no-floppy --recheck --target=x86_64-efi --force-extra-removable --root-directory=$grub_root --efi-directory=$grub_root/boot/efi --bootloader-id="$bootloader_name" --no-uefi-secure-boot 2>&1)
         umount $grub_root/boot/efi
         ##TODO DO we need these to be in fstab??
         #
         #This is what I've used in the past
         #if [ $I -gt 0 ]; then
         #    RAIDPART="#"
         #fi
         #echo "${RAIDPART}PARTUUID=$(blkid -s PARTUUID -o value $part) /boot/efi vfat defaults 0 1" >> /etc/fstab
     done
     rm /tmp/efiparts.tmp
  else   
      if [[ $grub_inst_drv == "md raid" ]]; then
        for slave in $raid_slaves; do
          grub_inst_drv=${slave:0:3}
          output=$(grub-install --no-floppy --recheck --root-directory=$grub_root \
              /dev/$grub_inst_drv 2>&1)
          lecho "$output"
        done
      else
        output=$(grub-install --no-floppy --recheck --root-directory=$grub_root \
            /dev/$grub_inst_drv 2>&1)
        lecho "$output"
      fi
  fi
      
  progress_indicator stop

  output=$(/opt/vyatta/sbin/vyatta-grub-setup $grub_setup_args \
             "$ROOT_PARTITION" '' $grub_root 2>&1)
  ret=$?
  lecho "$output"
  if [ $ret == 0 ]; then
    echo 'OK'
  else
    echo 'Grub failed to install!'
    exit 1
  fi
}

setup_xen_extras () {
    echo "Setting up config files for Xen..."

    # Get the root device that will hold the root filesystem
    rootdev="xvda1"
    echo -n "Root filesystem device [$rootdev]: "
    response=$(get_response "$rootdev");
    rootdev=$response
    echo "Using $rootdev"

    # Set up /boot/grub/menu.lst for use by pygrub
    grubfile=$grub_root/boot/grub/menu.lst
    echo "timeout 5" >> $grubfile
    echo "" >> $grubfile
    echo "title    vyatta-virt" >> $grubfile
    echo "root     (hd0,0)" >> $grubfile
    echo "kernel   $xen_grub_boot_path/vmlinuz root=/dev/$rootdev boot=live vyos-union=$xen_grub_boot_path console=hvc0" >> $grubfile
    echo "initrd   $xen_grub_boot_path/initrd.img" >> $grubfile

    # Add symlink pointing to default image
    ln -s $image_name $grub_root/boot/%%default_image

    # Add console port entry for the Xen PV console
    add_console_entry hvc0 "${INST_ROOT}${VYATTA_CFG_DIR}/config.boot"
}

check_for_xen_extras () {
    manuf=`/usr/sbin/dmidecode -s system-manufacturer`
    prod=`/usr/sbin/dmidecode -s system-product-name`
    if [ "$manuf" = "Xen" -a "$prod" = "HVM domU" ]; then
        echo "You are installing to a $manuf $prod virtual machine."
        echo "Would you like to set up config files to prepare for the"
        echo -n "conversion to PV domU? [No]: "
        response=$(get_response "No" "Yes No Y N")
        if [ "$response" == "yes" ] || [ "$response" == "y" ]; then
            setup_xen_extras
        fi
    fi
}

#####  Main

version=$(get_new_version)
if [ -z "$version" ]; then
  echo 'Cannot find new version. Exiting...'
  exit 1
fi

array=( $WRITE_ROOT/boot/* )
image_name=${array[0]}
image_name=${image_name#$WRITE_ROOT/boot/}

# these are the defaults for "union"
grub_root=$WRITE_ROOT
grub_setup_args="-u $image_name"
xen_grub_boot_path="/boot/%%default_image"
if [ "$INSTALL_TYPE" == 'old' ]; then
  grub_root=$INST_ROOT
  grub_setup_args="-v $version"
  xen_grub_boot_path="/boot"
elif [ "$INSTALL_TYPE" != 'union' ]; then
  echo 'Invalid install type. Exiting...'
  exit 1
fi

# Copy the config files saved from earlier steps
copy_config

# Modify config to match system
# Assume user wants to keep password from old config
if [ ! -d /mnt/config ]; then
  # Disable root login
  set_encrypted_password root "*" "${INST_ROOT}${VYATTA_CFG_DIR}/config.boot"

  echo "Enter password for administrator account"
  change_password $DEFAULT_USER "${INST_ROOT}${VYATTA_CFG_DIR}/config.boot"
fi

# Install grub
install_grub

if [ ! -d /sys/firmware/efi ]; then
    # Perform additional configuration if installing on Xen
    check_for_xen_extras
fi

#
# Only start the mdadm daemon if we have the root filesystem running
# on a RAID set.  Since this script is the only way that the root filesystem
# ever gets set up, we can do this configuration here.
#
MDADM_CONFIG_FILE=${INST_ROOT}/etc/default/mdadm
if [ -f "$MDADM_CONFIG_FILE" ]; then
  if [ "${INSTALL_DRIVE:0:2}" = "md" ]; then
    sed -i -e 's/^START_DAEMON.*$/START_DAEMON=true/' \
	-e 's/^AUTOSTART=.*$/AUTOSTART=true/' $MDADM_CONFIG_FILE
  else
    sed -i -e 's/^START_DAEMON.*$/START_DAEMON=false/' \
	   -e 's/^AUTOSTART=.*$/AUTOSTART=true/' $MDADM_CONFIG_FILE
  fi
fi

if [ "$INSTALL_TYPE" != 'union' ]; then
  WRITE_ROOT=''
fi

becho "Done! Please reboot now."

exit 0

