#!/bin/bash
# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# ex: ts=8 sw=4 sts=4 et filetype=sh

set -e

UNIT_DIR="${1:-/tmp}"

cmdline=( $(</proc/cmdline) )
cmdline_arg() {
    local name="$1" value="$2"
    for arg in "${cmdline[@]}"; do
        if [[ "${arg%%=*}" == "${name}" ]]; then
            value="${arg#*=}"
        fi
    done
    echo "${value}"
}

# check *both* old and new keys for now
platform_id=$(cmdline_arg ignition.platform.id "$(cmdline_arg coreos.oem.id)")

cmdline_bool() {
    local value=$(cmdline_arg "$@")
    case "$value" in
        ""|0|no|off) return 1;;
        *) return 0;;
    esac
}

add_requires() {
    local name="$1"; shift
    local requires_dir="${UNIT_DIR}/initrd.target.requires"
    mkdir -p "${requires_dir}"
    ln -sf "../${name}" "${requires_dir}/${name}"
}

# This can't be done with ConditionKernelCommandLine because that always
# starts the unit's dependencies. We want to start networking only on first
# boot.
if $(cmdline_bool 'ignition.firstboot' 0); then
    add_requires ignition-complete.target
fi

RANDOMIZE_DISK_GUID=$(cmdline_arg coreos.randomize_disk_guid)
if [ -n "$RANDOMIZE_DISK_GUID" ]; then
    escaped_guid=$(systemd-escape --path "/dev/disk/by-diskuuid/$RANDOMIZE_DISK_GUID")
    add_requires "disk-uuid@${escaped_guid}.service"
fi

echo "PLATFORM_ID=$platform_id" > /run/ignition.env
