#!/bin/sh
# $Id: autoinst.sh,v 1.6.1.10 2014/12/02 20:03:43 asau Stab $
set -e

_progname="${0##*/}"
usage="usage: ${0##*/} [-s swap-size-mb] [-S swap-size-blocks] device-name"

SWAPSIZE=
while getopts "s:S:" opt; do
    case $opt in
	s) SWAPSIZE=$((2 "*" 1024 "*" ${OPTARG}));; # swap size in MiB
	S) SWAPSIZE=$((0 + ${OPTARG}));;
	\?) echo "$usage" 1>&2; exit 1;;
    esac
done
shift $(expr $OPTIND - 1)

if [ $# != 1 ]; then echo "$usage" 1>&2; exit 1; fi

#
SD=$1 # storage device
: ${SWAPSIZE:=$((2 "*" 1024 "*" 16))} # default to 16 MiB

# Path to installation sets:
: ${OBJDIR:=/usr/obj}
: ${RELEASEDIR:=${OBJDIR}/releasedir}
: ${SETSDIR:=${RELEASEDIR}/$(uname -m)/binary/sets}

: ${TMPDIR:=/tmp} # temporary directory

# Disk partitioning
SIZE=$(fdisk ${SD} 2>/dev/null | sed -ne '/^total sectors:/{s/^[^:]*[^0-9]*//;s/[^0-9].*$//;p;q;}')
fdisk -f -v -u -i -0 -a -s 169/64/$(($SIZE - 64)) ${SD}
fdisk -f -c /usr/mdec/mbr ${SD}

# Extract BSD label:
label=${TMPDIR}/${_progname}.label.$$
disklabel ${SD} >${label} ||: # ignore error status, the label doesn't exist usually
# Replace partition data in BSD label:
ed -s ${label} <<EOF
/^$/
+,\$d
a
4 partitions:
#        size                    offset     fstype [fsize bsize cpg/sgs]
 a: $(($SIZE - $SWAPSIZE - 64))      64     4.2BSD      0     0     0
 b: ${SWAPSIZE}  $(($SIZE - $SWAPSIZE))       swap
 c: $(($SIZE - 64))                  64     unused      0     0
 d: ${SIZE}                           0     unused      0     0
.
w
q
EOF
# Write BSD label back:
disklabel -R ${SD} ${label}
rm -f ${label}

mnt=${TMPDIR}/${_progname}.$$

# Now create file systems, and unpack sets
newfs -O2 ${SD}a
mkdir ${mnt}
mount /dev/${SD}a ${mnt}

cd ${mnt}
for s in base etc; do pax -zrpe -f ${SETSDIR}/$s.tgz; done
for s in kern-GENERIC modules; do pax -zrpe -f ${SETSDIR}/$s.tgz; done

# Make it bootable:
cp usr/mdec/boot .
installboot -vf -o timeout=2 /dev/r${SD}a /usr/mdec/bootxx_ffsv2
# ...only make sure that this boot code corresponds to file system in newfs above.

# Populate /dev
(cd dev && sh MAKEDEV all)

# Additional mount points:
mkdir proc kern

# Generate fstab
cat > etc/fstab <<EOF
/dev/wd0a / ffs rw,log 1 1
/dev/wd0b none swap sw 0 0
ptyfs /dev/pts ptyfs rw
kernfs /kern kernfs rw
procfs /proc procfs rw
tmpfs /tmp tmpfs rw
EOF

# Generate rc.conf
cat > etc/rc.conf <<EOF
if [ -r /etc/defaults/rc.conf ]; then
	. /etc/defaults/rc.conf
fi
rc_configured=yes
EOF

# Wrap up:
sync
cd # don't hold file system
umount ${mnt}
rmdir ${mnt}
