#!/bin/sh -e
# --------------------------------------------------------------------
# Copyright © 2014 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------

# Writable changes are possible on the read-only root filesystem since
# the initramfs creates a read-only bind mount *on top* of the real
# read-only root filesystem mount.
#
# This bind mount acts as an insulating layer/cloak, hiding any
# superblock changes (as made by this script) from the main system.

if [ $# -lt 1 ]
then
    echo "ERROR: need command-file" >&2
    exit 1
fi

cat << EOT | unshare --mount -- /bin/sh -e

# Peel back the read-only bind mount layer added by the initramfs to
# allow changes to be made to the underlying filesystem.
echo "$0: I: preparing root filesystem"
umount /

# Make root filesystem writable.
#
# This change is invisible to the rest of the system, since it is
# operating in the _original_ mount namespace (where the read-only
# bind mount on top of the real read-only mount below it masks this
# change).
mount -o remount,rw /

# Check the newly-downloaded image, then unpack it on top of the root
# filesystem.
echo "$0: I: applying system image update"
/usr/bin/ubuntu-core-apply $@
sync

# Reinstate read-only rootfs in this mount namespace. 
#
# Note that this operation appears to be redundant (since we are about
# to destroy the new mount namespace), but it seems safer to
# restore the original "mount stack" since the live system is relying on
# it. It certainly shouldn't cause any problems being tidy :)
echo "$0: I: finalising"
mount -o remount,ro /

EOT
