#!/bin/sh
# Put the phone system on this machine's disk. Run from the live ISO.
#
# Alpine's own installer does the work; this wraps it so the questions a
# person cannot answer wrong are not asked. Keyboard, name, network, root
# password, time zone and the disk are asked, because nobody else can answer
# those. The machine reboots into the first boot, which does the rest.
set -eu

if [ "$(id -u)" != 0 ]; then
	echo "run this as root" >&2
	exit 1
fi

cat <<'TEXT'

  nuxpbx: install the phone system on this machine

  This will ask for the keyboard, a name for the machine, the network, a
  root password, the time zone, and which disk to use. THE DISK IS ERASED.

  After the reboot the machine sets itself up: the database, Asterisk and
  the phone system. The first administrator and the password are then in
  /root/nuxpbx-welcome. Sign in on port 8080 in a browser.

TEXT
printf 'Continue? [y/N] '
read -r answer
case "$answer" in y|Y|yes|YES|j|J|ja) ;; *) echo "nothing was changed"; exit 0 ;; esac

# The packages come from this medium, wherever it is mounted, so no mirror
# is needed and none is asked for; the first boot adds Alpine's mirror and
# the package repository for updates. SSH stays on: a phone system in a
# rack needs a way in without a screen.
media=$(grep '^/media/' /etc/apk/repositories | tr '\n' ' ')
[ -n "$media" ] || { echo "cannot find the packages on the boot medium (/etc/apk/repositories names none)" >&2; exit 1; }
answers=$(mktemp)
cat >"$answers" <<ANSWERS
APKREPOSOPTS="$media"
SSHDOPTS="openssh"
NTPOPTS="chrony"
USEROPTS="none"
ANSWERS

# The installed system carries this ISO's overlay with it: the package
# selection, the services enabled at boot, and the first boot that runs once.
setup-alpine -f "$answers"
rm -f "$answers"

cat <<'TEXT'

  Installed. Take the ISO out and reboot:  reboot

  The first boot takes a minute. Then read /root/nuxpbx-welcome.

TEXT
