#!/bin/bash
# combustion: network
# Redirect output to the console
# Example taken from https://en.opensuse.org/Portal:MicroOS/Combustion

exec > >(exec tee -a /dev/tty0) 2>&1

# Leave a marker
echo "openSUSE Leap based CBS Configured by SUSE IT combustion" > /etc/issue.d/combustion

# change by default unset root password to "suseit"
# generated by openssl passwd -6
echo 'root:$6$/Ipu/DzM1oX2MoYx$s/rxTh7yiTdduPaGUa4dht6.loJIUF84rYas///sguPOdqTphdfSv8ecGwMcsO4Zr1/y2Pr94TbHxume2b7pA0' | chpasswd -e

# TODO for the future tpm2!
#systemd-cryptenroll --wipe-slot=empty --tpm2-device=auto --tpm2-pcrs=4+7+8+9 /dev/sda3

# return line above "luks" match in lsblk output, strip any non-alphanumeric characters
# expected result e.g. /dev/nvme0n1p4

LUKSDEV="`lsblk | grep luks -B 1 |head -1 |  awk '{ print $1 }' | tr -cd '[:alnum:]._-'`"
DEFAULTPASSWD="suseit"
NEWLUKSPASSWD="pleasechangeme"

if [[ ! -z "$LUKSDEV" ]]; then
	echo -e "${DEFAULTPASSWD}\n${NEWLUKSPASSWD}\n${NEWLUKSPASSWD}" | cryptsetup luksChangeKey -S 0 "/dev/${LUKSDEV}"
echo "luksChangeKey passed" >> /etc/issue.d/combustion

else
	echo "WARNING: Could not find luks encrypted device. Skipping luksChangeKey" >> /etc/issue.d/combustion

fi

cat > /etc/sudoers <<-EOF
# Configured by SUSE IT combustion script
# https://github.com/SUSE/suse-csb-release

Defaults targetpw   # ask for the password of the target user i.e. root
ALL   ALL=(ALL) ALL   # WARNING! Only use this together with 'Defaults targetpw'!

Defaults always_set_home
Defaults secure_path="/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/bin:/usr/local/sbin"
Defaults env_reset
Defaults env_keep = "LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL LANGUAGE LINGUAS XDG_SESSION_COOKIE"
Defaults !insults
root ALL=(ALL:ALL) ALL
%wheel ALL=(ALL:ALL) ALL
@includedir /etc/sudoers.d
EOF

echo "INFO: SUSE IT owns the root access" >> /etc/issue.d/combustion
