#!/bin/bash
#
# Copyright (C) 2015-2016 Red Hat, Inc.
#
# This file is part of atomic-devmode.
#
# atomic-devmode is free software: you can redistribute it
# and/or modify it under the terms of the GNU Lesser General
# Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# atomic-devmode is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU Lesser General Public License for
# more details.
#
# You should have received a copy of the GNU Lesser General
# Public License along with atomic-devmode. If not, see
# <http://www.gnu.org/licenses/>.

set -euo pipefail

SHARE=/usr/share/atomic-devmode
LIBEXEC=/usr/libexec/atomic-devmode

# Really, only the getty stuff needs to be in bootcmd. The
# rest can safely be executed later in runcmd. However,
# there seems to be a bug in cloud-init which for some
# reason doesn't let runcmd run on every boot, even after
# overriding the frequency to 'always'.

# witness file to tell scripts we're in devmode
touch /run/atomic-devmode

# 1. set up getty override

# We use a bind mount here so that it's only valid for this
# boot.

getty_override_dir=/etc/systemd/system/getty@tty1.service.d
mkdir -p $getty_override_dir
touch $getty_override_dir/override.conf
mount --bind $SHARE/getty-override.conf $getty_override_dir/override.conf

# make systemd see the override
systemctl daemon-reload

# restart the getty service if it's already running
systemctl try-restart getty@tty1.service

# 2. set up bash profile

# Here too, use bind mount to make this temporary.

if ! test -f /root/.bash_profile; then
	touch /root/.bash_profile
fi
cp -a /root/.bash_profile /run/atomic-devmode-bash-profile # copy selinux label
cat $LIBEXEC/bash_profile >> /run/atomic-devmode-bash-profile
mount --bind /run/atomic-devmode-bash-profile /root/.bash_profile

# 3. root password

# We autogen a root password and change it. Speaking with
# cloud-init devs, it has the functionality to autogen a
# passwd, but the pw just gets lost (it's printed on stderr,
# but masked in the journal logs). So there is no way for us
# to pick it up so we can print later on.

$LIBEXEC/pwmake_friendly 64 \
	| tee /run/atomic-devmode-root \
	| passwd --stdin root >/dev/null
chmod 600 /run/atomic-devmode-root
passwd -u root >/dev/null

# 4. sshd configuration

# We have to make sure that sshd accepts challenge-response
# authentications so that password resets can be carried out
# over the Cockpit login. We bind mount a copy over the
# original config so that we don't affect it.

cp -a /etc/ssh/sshd_config /run/atomic-devmode-sshd-config # copy selinux label
sed -i 's/^\(ChallengeResponseAuthentication\) .*/\1 yes/I' \
	/run/atomic-devmode-sshd-config
mount --bind /run/atomic-devmode-sshd-config /etc/ssh/sshd_config

systemctl try-restart sshd.service
