#!/bin/csh

if ( "" == "$1" ) then
  echo 'Usage: postinstall <target_directory>'
  echo 'Environment variables:'
  echo '$POSTINSTALL - name of the script to execute instead of this one'
  echo '$ROOTDEV - block device with root filesystem (for bootloader install)'
  echo '$ROOT_SSH_KEY - line for adding to ~root/.ssh/authorized_keys'
  exit 1
endif

set target="$1"

if ( ! -d "$target" ) then
  echo "Target directory doesn't exist"
  exit 1
endif

sync
umask 022

if ( $?POSTINSTALL ) then
  test -x "$POSTINSTALL" && exec "$POSTINSTALL" "$1"
  exit 0
endif

chroot "$target" usermod -p '' -s /bin/tcsh root
# ssh-keygen needs /dev/random; extlinux needs /dev/$ROOTDEV
chroot "$target" mount -t devtmpfs /dev /dev
chroot "$target" ssh-keygen -A
chroot "$target" chkconfig --add sshd
if ( ${?ROOTDEV} ) then
  ln -s "$ROOTDEV" "$target/dev/root"
  chroot "$target" extlinux -r -i /boot
else
  # Use placeholder if the variable is not provided
  set ROOTDEV="root"
endif
chroot "$target" umount /dev

cat << __FSTAB_EOF__ > "$target/etc/fstab"
/dev/$ROOTDEV		/		auto	defaults			0 1
proc		/proc		proc	nosuid,noexec,gid=proc		0 0
devpts		/dev/pts	devpts	nosuid,noexec,gid=tty,mode=620	0 0
tmpfs		/tmp		tmpfs	nosuid				0 0
__FSTAB_EOF__

# check for real hardware behind serial TTYs and activate them
foreach serial ( S0 S1 S2 S3 )
  stty -F "/dev/tty$serial" -g >& /dev/null \
  && echo "$serial:2345:respawn:/sbin/mingetty tty$serial" \
    >> "$target/etc/inittab"
  grep "^tty$serial" "$target/etc/securetty" \
  || echo "tty$serial" >> "$target/etc/securetty"
end

# find all possible SSH keys and put them to /root/.ssh/authorized_keys
# on a freshly installed system - that may be excessive, but guarantees
# the server will be accessible
set akeys=`mktemp`
mkdir -p "$target/root/.ssh"
touch "$target/root/.ssh/authorized_keys"
test -s ~/.ssh/id_ed25519.pub && cat ~/.ssh/id_ed25519.pub >> "$akeys"
test -s ~/.ssh/id_rsa.pub && cat ~/.ssh/id_rsa.pub >> "$akeys"
test -s ~/.ssh/authorized_keys \
&& grep '^ssh-' ~/.ssh/authorized_keys >> "$akeys"
test -s /root/.ssh/authorized_keys \
&& grep '^ssh-' /root/.ssh/authorized_keys >> "$akeys"
if ( $?ROOT_SSH_KEY ) then
  test -n "$ROOT_SSH_KEY" && echo "$ROOT_SSH_KEY" >> "$akeys"
endif
cat "$akeys" | sort | uniq > "$target/root/.ssh/authorized_keys"
rm -f "$akeys"
