#!/bin/sh

# Get a clean image
dd if=/dev/xbd5 bs=128k | gzip -9 > /image.gz

# Extract and mount onto /mnt
mdconfig -a -t swap -s 10G -u 0
gunzip < /image.gz | dd of=/dev/md0 bs=128k
mount /dev/md0p2 /mnt

# We'll want awscli in the AMI builder
env ASSUME_ALWAYS_YES=YES pkg -r /mnt install awscli

# Don't want fortune running at ssh login
chmod a-x /mnt/usr/games/fortune

# Which FreeBSD release is this?
VERS=`/mnt/bin/freebsd-version`

# Move /boot /usr /var /tmp onto a second disk so that it can be
# loaded into memory after the kernel boot completes
DISK2BITS="boot usr var tmp"
tar -czf /bits.tgz -C /mnt ${DISK2BITS} -C / image.gz
for D in ${DISK2BITS}; do
	chflags -R noschg /mnt/${D}
	rm -r /mnt/${D}
	ln -s /bits/${D} /mnt/${D}
done

# Mountpoints
mkdir /mnt/boot.disk /mnt/bits

# When we moot from the mfsroot, it will be /dev/md0
# Configuration for the AMI-building image
cat >/mnt/etc/fstab <<EOF
/dev/md0 / ufs rw 1 1
EOF

# With / being on a memory disk, these would screw things up
cat >>/mnt/etc/rc.conf <<EOF
firstboot_freebsd_update_enable="NO"
firstboot_pkgs_enable="NO"
growfs_enable="NO"
EOF

# Re-purpose rc.initdiskless since it runs early in the boot process
touch /mnt/etc/diskless
cat >/mnt/etc/rc.initdiskless <<EOF
mount -u /
echo "Loading FreeBSD into memory disk..."
mount /dev/ada0p2 /boot.disk
mdconfig -a -t swap -s 10G -u 1
newfs /dev/md1
mount /dev/md1 /bits
/rescue/tar -xf /boot.disk/bits.tgz -C /bits
umount /boot.disk
rmdir /boot.disk
echo "Installing base FreeBSD image..."
gunzip < /bits/image.gz | dd of=/dev/ada0 bs=128k
rm /bits/image.gz
gpart recover /dev/ada0
gpart resize -i 2 /dev/ada0
growfs -y /dev/ada0p2
echo '/dev/ada0p2 /mnt ufs rw 0 0' >> /etc/fstab
mount -ur /
mount /mnt
EOF

# Basic instructions in motd
cat >/mnt/etc/motd <<EOF
Welcome to the FreeBSD AMI builder!

FreeBSD ${VERS} is now installed onto the disk /dev/ada0, and
mounted at /mnt. Make any further you wish, then run

# mkami <AMI name> [<AMI description>]

to create the AMI. Don't forget to shut down this instance when
you're done!

EOF

# The AMI-building script
cat > /mnt/bin/mkami <<'EOF'
#!/bin/sh -e

export PATH=$PATH:/usr/local/bin

NAME=$1
if [ -z "$NAME" ]; then
        echo "usage: mkami <AMI name> [<AMI description>]"
        exit 1
fi
DESC=$2
if ! [ -z "$DESC" ]; then
        DESCOPT="--description '$DESC'"
fi

TMPFILE=`mktemp`
fetch -qo $TMPFILE http://169.254.169.254/latest/dynamic/instance-identity/document
INST=`awk -F \" '/"instanceId"/ { print $4 }' $TMPFILE`
REGION=`awk -F \" '/"region"/ { print $4 }' $TMPFILE`
rm $TMPFILE
CMD="aws --region $REGION ec2 create-image --instance-id $INST --output text --no-reboot --name '$NAME' $DESCOPT"

# Unmount /mnt if it is mounted
if mount -p | awk '{ print $2 }' | grep -q '^/mnt$'; then
        echo -n "Unmounting /mnt..."
        # Be paranoid about making sure bits get to disk
        sync; sync; sync;
        umount /mnt
        sync; sync; sync;
        sleep 5
        sync; sync; sync;
        echo " done."
fi

if eval "$CMD" --dry-run 2>&1 | grep -q UnauthorizedOperation; then
        echo "This EC2 instance does not have permission to create AMIs."
        echo "Launch an AMI-builder instance with an appropriate IAM Role,"
        echo "create an AMI from this instance via the AWS Console, or run"
        echo "the following command from a system with the necessary keys:"
        echo
        echo "$CMD"
        exit 0
fi

echo -n "Creating AMI..."
AMINAME=`eval "$CMD"`
echo " done."
echo "AMI created in $REGION: $AMINAME"
EOF
chmod 755 /mnt/bin/mkami

# Build mfsroot and clean up
makefs -b 10% -f 10% /mfsroot /mnt
gzip -9 /mfsroot
umount /mnt
mdconfig -d -u 0

# We want to boot from the mfsroot
cat >>/boot/loader.conf <<EOF
mfsroot_load="YES"
mfsroot_type="mfs_root"
mfsroot_name="/mfsroot"
vfs.root.mountfrom="ufs:/dev/md0"
EOF

# Shut down so that AMI can be created
shutdown -p now
