#!/bin/bash
set -x -e
HOST_DIR="${HOST_DIR:-/host}"
RELEASE_FILE="${RELEASE_FILE:-/etc/os-release}"
CONF_FILE="${CONF_FILE:-/run/data/cloud-config}"

function config()
{
    if [ ! -s $CONF_FILE ]; then
        if [ -e ${HOST_DIR}/oem/90_operator.yaml ]; then
            rm -f ${HOST_DIR}/oem/90_operator.yaml
            $REBOOT
        fi
        return 0
    fi

    if [ ! -e ${HOST_DIR}/oem/90_operator.yaml ] || ! diff $CONF_FILE ${HOST_DIR}/oem/90_operator.yaml >/dev/null; then
        cp -f $CONF_FILE ${HOST_DIR}/oem/90_operator.yaml
        $REBOOT
    fi
}

if [ "$FORCE" != "true" ]; then
    if diff $RELEASE_FILE ${HOST_DIR}${RELEASE_FILE} >/dev/null; then
        echo Update to date with
        cat ${RELEASE_FILE}

        REBOOT="nsenter -i -m -t 1 -- reboot"
        config
        exit 0
    fi
fi

config
mount --rbind $HOST_DIR/dev /dev
mount --rbind $HOST_DIR/run /run
elemental upgrade --system.uri dir:/

# After elemental upgrade we have to also copy
# /etc/resolv.conf from /host filesystem, otherwise 
# it will be taken from container context
mount -o remount,rw /run/initramfs/cos-state
LOOP_DEV=$(losetup -f)
losetup $LOOP_DEV /run/initramfs/cos-state/cOS/active.img
mkdir -p /tmp/cOS
mount $LOOP_DEV /tmp/cOS
rsync -av $HOST_DIR/etc/resolv.conf /tmp/cOS/etc/resolv.conf
umount /tmp/cOS
losetup -d $LOOP_DEV

nsenter -i -m -t 1 -- reboot
exit 1
