#!/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 pentoo
}

x_or_no(){
  portageq has_version / pentoo-desktop || return 1
  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 "For your security, Pentoo does not come with a default password.\n"
  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 pentoo
  if [ -r /etc/issue.pentoo.logo ]; then
    sudo cp /etc/issue.pentoo.logo /etc/issue
  else
    sudo cp /etc/issue /etc/issue.old
    printf "Welcome to Pentoo Live!\n" | sudo tee /etc/issue > /dev/null
  fi
  printf "Username is \"pentoo\", 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
x_or_no
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
  #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
  sudo /etc/init.d/xdm restart; sudo /etc/init.d/xdm restart && exit 0
else
  exec /bin/bash -l
fi
