#!/bin/sh
# tty1 로그인 화면 (inittab 에서 getty 대신 실행).
# 관리자 비밀번호가 아직 없으면 웹 첫 설정 주소를 보여 주고(10초마다 갱신),
# Enter 를 누르면 이 화면에서 바로 비밀번호를 정할 수도 있다. 정해지면 평소 로그인 화면(getty)으로.
# 콘솔은 한글을 표시하지 못해서 메시지는 영어.

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

banner() {
	ip=$(ip -4 -o addr show scope global 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | grep -v '^172\.1[78]\.' | head -n1)
	host=$(hostname)
	clear
	cat <<EOF

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

  On another computer or phone, open a web browser and go to:

      https://$host.local
      https://${ip:-(waiting for network...)}

  The browser will warn that the connection is not private
  (the NAS made its own certificate). Choose to continue.

  The setup page asks for the admin password, NAS name,
  time zone and network settings.

  No other computer? Press Enter to set the admin password here.

EOF
}

set_password_here() {
	clear
	cat <<'EOF'

  Choose a password for the administrator account 'admin'.
  * 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 "  The other settings (name, network...) can still be done in the browser."
	echo
	sleep 3
}

while [ -e "$NEEDS" ]; do
	banner
	# Enter 를 누르면 여기서 설정, 아니면 10초마다 화면 갱신 (IP 가 늦게 잡히거나 웹에서 설정을 마쳤을 때)
	if read -t 10 -r _; then
		[ -e "$NEEDS" ] && set_password_here
	fi
done

exec /sbin/getty 38400 tty1
