#!/bin/sh
setpassword(){
  printf "RFC 2119: MUST means an absolute requirement\n"
  printf "You *MUST* set a password to continue. Do not forget your password.\n"
  sudo passwd "${changeuser}"
}

x_or_no(){
  if [ ! -x "/etc/init.d/xdm" ] && [ ! -x "/etc/init.d/display-manager" ]; then
    return 1
  fi
  printf "Would you like to securely start X now?\n"
  printf "[y/n] "
  read -r choose_x
  case ${choose_x} in
    y|n) printf "${choose_x}\n";;
    *) printf "only y or n accepted\n"
      x_or_no
      ;;
  esac
}

changeuser="${USER}"

if sudo grep -q "${changeuser}:!" /etc/shadow; then
  printf "To protect your session you must set a password now.\n"
  printf "Do not forget your password.\n"
  sudo passwd "${changeuser}"
fi

while sudo grep -q "${changeuser}:!" /etc/shadow; do
  setpassword
done

printf "\nRemember your password, you will need it to log in as user \"${changeuser}\"\n"

if ! sudo grep -q "${changeuser}:!" /etc/shadow; then
  # restore real inittab and tell init about it
  if [ -r /etc/inittab.old ]; then
    sudo mv /etc/inittab.old /etc/inittab
    sudo init q
  fi

  #update /etc/issue to remind users to log in as ${changeuser}
  printf "Username is \"${changeuser}\", password is whatever you set at boot.\n" | sudo tee -a /etc/issue > /dev/null

  #we have set the password, pull livecd-setpass out of bashrc, our work is done
  grep -v livecd-setpass ~/.bashrc > .bashrc_setpass_temp
  mv .bashrc_setpass_temp ~/.bashrc
else
  printf "Something went wrong, aborting password set.  Please report this issue\n"
fi
RAMSIZE=$(awk '/MemTotal/ {printf( "%.0f\n", int ( $2 / 1024 ) + 1)}' /proc/meminfo)
if [ "${RAMSIZE}" -gt "700" ]; then
  x_or_no
else
  printf "Your system doesn't have enough ram to run X properly.  Please increase the amount of ram if possible.\n"
  choose_x="n"
fi
if [ "${choose_x}" = "y" ]; then
  printf "Remember to log in with user \"${changeuser}\" and the password you just set\n"
  printf "*Press any key to start X securely.*\n"
  read -r
  if [ -f "/etc/.noxdm" ]; then
    #livecd-tools autoconfig starts X by default, but xdm won't start the first time if nox is passed
    #because nox boot param was passed we have to start xdm twice to make it work or just delete the canary
    rm -f "/etc/.noxdm"
  fi
  if [ -x "/etc/init.d/display-manager" ]; then
    sudo /etc/init.d/display-manager restart && exit 0
  elif [ -x "/etc/init.d/xdm" ]; then
    sudo sudo /etc/init.d/xdm restart && exit 0
  fi
else
  exec /bin/bash -l
fi
