#!/bin/sh -efu

# don't cripple the image to be copied over
[ -n "${GLOBAL_LIVE_INSTALL-}" ] || \
	[ -x /usr/sbin/live-install ] || \
	[ -x /usr/sbin/livecd-install ] && exit 0

which rescue-shell-show >/dev/null 2>&1 || exit 0

# for systemd only
ls -l /sbin/init |grep -q systemd || exit 0

# disable issue "Hello friend, say '$LIVECD_LOGIN' to log in at"
[ ! -f /etc/sysconfig/livecd-user.conf ] ||
    echo 'LIVECD_NO_ISSUE=1' >> /etc/sysconfig/livecd-user.conf

# Autologin root to tty's
mkdir -p /etc/systemd/system/getty@.service.d
cat>>/etc/systemd/system/getty@.service.d/live-rescue.conf<<'EOF'
[Service]
ExecStart=
ExecStart=-agetty -o '-p -f -- \\u' --noclear --autologin root %I $TERM
EOF

# Autologin root to serial tty's
mkdir -p /etc/systemd/system/serial-getty@.service.d
cat>>/etc/systemd/system/serial-getty@.service.d/live-rescue.conf<<'EOF'
[Service]
ExecStart=
ExecStart=-agetty -o '-p -f -- \\u' --keep-baud 115200,57600,38400,9600 --autologin root %I $TERM
EOF

mkdir -p /etc/systemd/system/live-rescue.target.d
cat>>/etc/systemd/system/live-rescue.target<<'EOF'
[Unit]
Description=Live Rescue System
Documentation=man:systemd.special(7)
Requires=basic.target network-online.target getty.target
Conflicts=rescue.service rescue.target multi-user.target
Conflicts=altlinux-first_time.service vconsole-setup-kludge@tty1.service
Before=altlinux-first_time.service vconsole-setup-kludge@.service
After=basic.target rescue.service rescue.target multi-user.target
After=getty.target
AllowIsolate=yes
EOF

cat>>/root/.bash_profile<<'EOF'
if grep -qs 'systemd.unit=live-rescue.target' /proc/cmdline; then
	if grep -wqs autorun /proc/cmdline; then
		if which rescue-launcher >/dev/null 2>&1; then
			if [ "$(tty 2>/dev/null)" = "/dev/tty1" ]; then
				rescue-launcher "$@"
			fi
		fi
	fi
	which rescue-shell-show >/dev/null 2>&1 && rescue-shell-show
fi
EOF
