#!/bin/bash

set -euo pipefail

. /usr/lib/coreos/generator-lib.sh

write_dropin() {
    local service="$1"; shift
    local args="$1"; shift

    local out_dir="${UNIT_DIR}/${service}.d"
    mkdir -p "${out_dir}"

    # /tmp isn't r/w yet, and the shell needs to cache the here-document
    TMPDIR=/run
    cat > "${out_dir}/10-autologin.conf" <<EOF
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin core -o '-p -f core' ${args} %I \$TERM
EOF
}

write_interactive_live_motd() {
    # Write motd to a tmp file and not directly to /etc/motd because
    # SELinux denies write from init_t to etc_t
    cat <<EOF > /run/interactive-live-motd

###########################################################################
Welcome to the CoreOS live environment. This system is running completely
from memory, making it a good candidate for hardware discovery and
installing persistently to disk. Here is an example of running an install
to disk via coreos-installer:

sudo coreos-installer install /dev/sda \\
    --ignition-url https://example.com/example.ign

You may configure networking via 'sudo nmcli' or 'sudo nmtui' and have
that configuration persist into the installed system by passing the
'--copy-network' argument to 'coreos-installer install'. Please run
'coreos-installer install --help' for more information on the possible
install options.
###########################################################################

EOF
    # Create coreos-cp-interactive-live-motd.service to copy over the motd in
    # place. Note this intentionally overwrites the existing motd, which is
    # blank on FCOS and populated on RHCOS.
    service="coreos-cp-interactive-live-motd.service"
    cat <<EOF > "${UNIT_DIR}/${service}"
# generated by coreos-liveiso-autologin-generator
[Unit]
Description=Copy CoreOS Interactive Live MOTD
Before=systemd-user-sessions.service
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/cp -v /run/interactive-live-motd /etc/motd
EOF
    mkdir -p "${UNIT_DIR}/multi-user.target.wants"
    ln -sf "../${service}" "${UNIT_DIR}/multi-user.target.wants/"
}

# Only allow automatic autologin on live systems
if [ ! -e /run/ostree-live ]; then
    exit 0
fi

# Autologin on ISO boots but not PXE boots.  The only way to tell the
# difference is a kernel argument.
if ! have_karg coreos.liveiso; then
    exit 0
fi

# If the user supplied an Ignition config, they have the ability to enable
# autologin themselves.  Don't automatically render them insecure, since
# they might be running in production and booting via e.g. IPMI.
if jq -e .userConfigProvided /etc/.ignition-result.json &>/dev/null; then
    exit 0
fi

write_dropin "getty@.service"        "--noclear"
# Also autologin on serial console if someone enables that
write_dropin "serial-getty@.service" "--keep-baud 115200,38400,9600"

# Write an motd that will let the user know about the live environment
# and what is possible.
write_interactive_live_motd
