#!/bin/sh

set -eu

cleanup() {
  stty echo
}

trap cleanup 0 INT TERM

while true; do
  stty echo

  printf 'Set root password: '
  stty -echo
  read root_password
  echo

  stty echo
  if [ -z "$root_password" ]; then
    echo 'Please provide a root password.'
    continue
  fi

  printf 'Set root password (again): '
  stty -echo
  read root_password_again
  echo

  stty echo
  if [ "$root_password" = "$root_password_again" ]; then
    printf "%s\n%s\n" "$root_password" "$root_password" \
      | passwd root 2>/dev/null
    install -o root -g root -m 600 /dev/null /state/.root_password.tmp
    awk -F: '$1 == "root" { print $2 }' /etc/shadow \
      > /state/.root_password.tmp
    mv /state/.root_password.tmp /state/.root_password
    exit 0
  fi

  echo 'Passwords do not match, try again.'
done
