#!/bin/bash -ex

. /root/config/chroot

# Specific ubuntu-image chroot configuration goes here.
if [ "$IMAGEFORMAT" == "none" ]; then
    if [ "$SUBPROJECT" == "desktop-preinstalled" ]; then
        # Create files/dirs Ubiquity requires
        mkdir -p /var/log/installer
        touch /var/log/installer/debug
        touch /var/log/syslog
        chown syslog:adm /var/log/syslog

        # Create the oem user account
        /usr/sbin/useradd -d /home/oem -G adm,sudo -m -N -u 29999 oem

        /usr/sbin/oem-config-prepare --quiet
        touch "/var/lib/oem-config/run"

        # Update the fstab to include the "discard" option, and
        # "x-systemd.growfs" to ensure the root partition is expanded on first
        # boot
        awk \
            -v root_fs_label="writable" \
            -v root_fs_options="discard,x-systemd.growfs" \
            '
        BEGIN { OFS="\t"; count=0; }

        # Omit the "UNCONFIGURED" warning if it is still present
        /^# UNCONFIGURED FSTAB/ { next; }

        # Only modify the first non-comment line where the second field is the
        # root and omit multiple root definitions
        /^[^#]/ && $2 == "/" {
            if (!count) {
                $1="LABEL=" root_fs_label;
                $4=root_fs_options;
                $6="1";
            }
            count++;
            if (count > 1) next;
        }

        { print; }

        # If we reach the end without seeing a root mount line, add one
        END {
            if (!count) {
                print "LABEL=" root_fs_label, "/", "ext4", root_fs_options, "0", "1";
            }
        }
        ' /etc/fstab > /etc/fstab.new
        mv /etc/fstab.new /etc/fstab

        # Add units for a 1GiB swapfile, generated on first boot
        cat << EOF > /lib/systemd/system/mkswap.service
[Unit]
Description=Create the default swapfile
DefaultDependencies=no
Requires=local-fs.target
After=local-fs.target
Before=swapfile.swap
ConditionPathExists=!/swapfile

[Service]
Type=oneshot
ExecStartPre=fallocate -l 1GiB /swapfile
ExecStartPre=chmod 600 /swapfile
ExecStart=mkswap /swapfile

[Install]
WantedBy=swap.target
EOF
        cat << EOF > /lib/systemd/system/swapfile.swap
[Unit]
Description=The default swapfile

[Swap]
What=/swapfile
EOF
        mkdir -p /lib/systemd/system/swap.target.wants
        ln -s ../mkswap.service /lib/systemd/system/swap.target.wants/
        ln -s ../swapfile.swap /lib/systemd/system/swap.target.wants/
    fi
fi