#!/bin/sh
# tty1 로그인 화면 (inittab 에서 getty 대신 실행).
# 관리자 비밀번호가 아직 없으면 먼저 두 번 입력받아 설정한 뒤, 평소의 로그인 화면(getty)으로 넘어간다.
# 부팅을 막지 않도록 OpenRC 서비스가 아니라 콘솔에서만 묻는다. 콘솔은 한글을 못 써서 메시지는 영어.

NEEDS=/etc/nasos/needs-password
MIN_LEN=6

if [ -e "$NEEDS" ]; then
	clear
	cat <<'EOF'

  ==============================================
   NAS OS - first time setup
  ==============================================

  Choose a password for the administrator account 'admin'.
  You will use it to log in here and over SSH (ssh admin@nasos.local).

  * Nothing is shown while you type. This is normal.
  * Keyboard layout is US. On a Mac, switch the input source to English (ABC).

EOF
	while :; do
		printf '  New password: '
		stty -echo
		read -r p1
		stty echo
		echo
		if [ "${#p1}" -lt "$MIN_LEN" ]; then
			echo "  Too short. Use at least $MIN_LEN characters."
			echo
			continue
		fi
		printf '  Retype password: '
		stty -echo
		read -r p2
		stty echo
		echo
		if [ "$p1" != "$p2" ]; then
			echo "  Passwords do not match. Please try again."
			echo
			continue
		fi
		if printf 'admin:%s\n' "$p1" | chpasswd 2>/dev/null; then
			break
		fi
		echo "  Could not set the password. Please try again."
		echo
	done
	p1=""
	p2=""
	rm -f "$NEEDS"
	logger -t nasos -p auth.notice "admin password set on console (first time setup)"
	echo
	echo "  Password set. Log in as 'admin' with this password."
	echo
	sleep 2
fi

exec /sbin/getty 38400 tty1
