#!/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 only if it doesn't already exist
        if ! id "oem" &>/dev/null; then
                /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"
        fi

        # Update the fstab to include the "discard" option
        awk \
            -v root_fs_label="writable" \
            -v root_fs_options="discard" \
            '
        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
    fi
fi