Partition automation in bsdinstall auto script in FreeBSD

[This post is part of the bsdinstall automation series. It should be read with the main article posted @ http://www.amitabhkant.com/custom_iso_with_bsdinstall_in_freebsd/]

These lines should go out in the bsdinstall auto file, after commenting out bsdinstall autopart and bsdinstall mount section. Remember, this would wipe out the entire disk contents without any warning, so use it at your own risk. I am also assuming that if you have multiple disks connected, the first disk is what you want to install your OS on. Otherwise, you might have to modify the script accordingly.

Get the disk layout, and the first disk connected to the system
# disk_layout=`sysctl -n kern.disks`
# first_disk=${disk_layout%% *}

Destroy any existing partition, and then create a gpt partition
# gpart destroy -F $first_disk
# gpart create -s gpt $first_disk

Create a boot partition to hold the loader, size of 512K. Give it a GPT label of gpboot, which will show up in /dev/gpt when the device is discovered:
# gpart add -t freebsd-boot -l gpboot -b 40 -s 512K $first_disk

Install the GPT bootcode into the boot partition:
# gpart bootcode -b /boot/pmbr -p /boot/gptboot -i 1 $first_disk

Create a swap parition
# gpart add -t freebsd-swap -l gpswap -s 4G $first_disk

Create a partition for /. It should start at the 1M boundary for proper sector alignment on 4K sector drives or SSDs. This is compatible with GPT drive layout for many other systems. Give it a GPT label of gprootfs.
# gpart add -t freebsd-ufs -l gprootfs -a 1M $first_disk

Format the root partition
# newfs -U /dev/gpt/gprootfs

Mount the partition at /mnt
# mount /dev/gpt/gprootfs /mnt

Add entry to fstab ($PATH_FSTAB)
# echo '# Device Mountpoint FStype Options Dump Pass#' > $PATH_FSTAB
# echo '/dev/gpt/gpswap none swap sw 0 0' >> $PATH_FSTAB
# echo '/dev/gpt/gprootfs / ufs rw 1 1' >> $PATH_FSTAB

(1) Although the post is meant as part of automating bsdinstall, the concept could be used to create partitions over a new disk with appropriate safeguards