#!/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