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

command -v getarg >/dev/null || . /usr/lib/dracut-lib.sh

set -e

# Generators don't have logging right now
# https://github.com/systemd/systemd/issues/15638
exec 1>/dev/kmsg; exec 2>&1

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

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

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

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

if [ -n "$(karg coreos.inst.install_dev)" ]; then
    ln -sf "/usr/lib/systemd/system/coreos-installer.target" \
        "${UNIT_DIR}/default.target"

    rm -rf /etc/initrd-release

    dmesg -n 1

    # Create precondition for coreos-installer-reboot.service if requested
    if ! karg_bool coreos.inst.skip_reboot; then
        > /run/coreos-installer-reboot
    fi
fi

# if we're not running in dracut, skip
if [ -z "$(karg coreos.inst.isoroot)" ]; then
    exit 0
fi

# isoroot is there but let's see if the raw image is online, skip iso mount otherwise
imgurl="$(karg coreos.inst.image_url)"
if [ -n "${imgurl}" ]; then
    echo "ISO root provided but image is online, skiping ISO mount"
    exit 0
fi

add_requires run-media-iso.mount default.target

isoroot=$(getarg coreos.inst.isoroot= ||:)

mkdir -p /run/media/iso
isosrc=dev/disk/by-label/${isoroot}
isosrc_escaped=$(systemd-escape -p --suffix=device "${isosrc}")

if [ -n "${isoroot}" ]; then
cat >"${UNIT_DIR}/run-media-iso.mount" <<EOF
# Automatically generated by live-generator
[Unit]
DefaultDependencies=false
# HACK for https://github.com/coreos/fedora-coreos-config/issues/437
Wants=systemd-udev-settle.service
Wants=systemd-udevd.service
After=systemd-udevd.service
After=basic.target
# Network is enabled here
After=nm-run.service
# compat: remove when everyone is on dracut 053+
After=dracut-initqueue.service

Before=coreos-installer.service
After=${isosrc_escaped}
Requires=${isosrc_escaped}
ConditionKernelCommandLine=coreos.inst.image_file
[Mount]
What=/${isosrc}
Where=/run/media/iso
Options=ro
Type=iso9660
EOF
fi