#!/bin/bash
# Generate the media-state.mount unit based on kernel parameters

set -e
DEST=/tmp

# Standard generator setup, they take three arguments but allow none too.
if [[ $# -gt 0 && $# -ne 3 ]]; then
    echo "This program takes three or no arguments." >&2
    exit 1
fi

# Use the first path provided, the "Normal" target for generators.
if [[ $# -gt 0 ]]; then
    TMPDIR="/run" # bash creates temp files in $TMPDIR for heredocs, but /tmp
                  # isn't a tmpfs yet when system-generators are run, so reuse
                  # /run.  Otherwise we'll fail if / is in a read-only state.
    DEST="$1"
fi

overlay_unit() {
    overlay_conf=$1
    out_dir="${DEST}/${overlay_conf}.d"
    out_file="${out_dir}/10-autologin.conf"
    mkdir -p "${out_dir}"
    if [[ "${overlay_conf}" == *serial* ]]; then
	cat << 'EOF' > "${out_file}"
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin core --keep-baud %I 115200,38400,9600 $TERM
EOF
    else
	cat << 'EOF' > "${out_file}"
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin core --noclear %I $TERM
EOF
    fi
}

# reconfigure emergency.service to autologin as root
emergency_autologin() {
    # only autologin if our tty is the active one
    grep -q "$1$" /sys/class/tty/console/active || return

    local out_dir="${DEST}/emergency.service.d"
    local out_file="${out_dir}/10-autologin.conf"
    mkdir -p "${out_dir}"
    cat << 'EOF' > "${out_file}"
[Service]
ExecStart=
ExecStart=-/bin/sh -c "/usr/bin/login -f root; /usr/bin/systemctl --job-mode=fail --no-block default"
EOF
}

autologin() {
    param="$1"
    arg=$(echo "${param}" | awk -F'=' '{print $2}')
    # if flatcar.autologin=ttyS*, override serial-getty@ttyS*.service.d
    if [[ "$arg" == *S* ]]; then
        overlay_unit "serial-getty@${arg}.service"
    # if flatcar.autologin=tty*, override getty@tty*.service.d
    elif [ -n "${arg}" ]; then
        overlay_unit "getty@${arg}.service"
    # if just flatcar.autologin, override serial-getty@.service.d and getty@.service.d
    elif [ -z "${arg}" ]; then
        overlay_unit "getty@.service"
        overlay_unit "serial-getty@.service"
    fi

    emergency_autologin "${arg}"
}

read -r CMDLINE </proc/cmdline;

for i in $CMDLINE; do
    prefix="$(echo "$i" | awk -F'.' '{print $1}')"
    if [ "$prefix" = "coreos" ] || [ "$prefix" = "flatcar" ]; then
        case "$i" in
             *.autologin*) autologin "$i" ;;
        esac
    fi
done

