#!/bin/bash
# Copyright (c) 2013 The CoreOS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# This is a simple check-in update_engine for PXE. Since the real update_engine
# can't run on rootless machines run this instead for now. This will be replaced
# by a new Go application that does kexec in place.

set -e -o pipefail

source /usr/share/flatcar/release
source /usr/share/flatcar/update.conf
if [[ -e /etc/flatcar/update.conf ]]; then
    source /etc/flatcar/update.conf
fi

for f in /usr/share/oem/oem-release /etc/oem-release; do
    if [[ -e $f ]]; then
        # Pull in OEM information too, but prefixing variables with OEM_
        eval "$(sed -e 's/^/OEM_/' $f)"
    fi
done

BOOT_ID=$(</proc/sys/kernel/random/boot_id)
MACHINE_ID=$(</etc/machine-id)
VERSION="${FLATCAR_RELEASE_VERSION}"

# Fill in default values
: ${FLATCAR_RELEASE_APPID:="{e96281a6-d1af-4bde-9a0a-97b76e56dc57}"}
: ${SERVER:="https://public.update.flatcar-linux.net/v1/update/"}
: ${GROUP:="alpha"}
: ${OEM_ID:="diskless"}
: ${MACHINE_ALIAS:=""}

fill_attrs() {
    echo -n "appid=\"${FLATCAR_RELEASE_APPID}\" "
    echo -n "oem=\"${OEM_ID}\" "
    echo -n "version=\"${VERSION}\" "
    echo -n "track=\"${GROUP}\" "
    echo -n "bootid=\"{${BOOT_ID}}\" "
    # other UUID's are surrounded by {} but not machineid
    echo -n "machineid=\"${MACHINE_ID}\" "
    echo -n "machinealias=\"${MACHINE_ALIAS}\" "
    echo -n "lang=\"en-US\" "
    echo -n "hardware_class=\"\" "
    echo -n "delta_okay=\"false\" "
}

BODY="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<request protocol=\"3.0\" version=\"FlatcarUpdateEngine-0.1.0.0\" updaterversion=\"FlatcarUpdateEngine-0.1.0.0\" installsource=\"scheduler\" ismachine=\"1\">
<os version=\"Chateau\" platform=\"CoreOS\" sp=\"${VERSION}\"></os>
<app $(fill_attrs) >
<event eventtype=\"3\" eventresult=\"2\" previousversion=\"\"></event>
</app>
</request>"

echo Request: "${BODY}"

curl -H "Content-Type: text/xml" -d "${BODY}" "${SERVER}"
