set -ex

SERIAL_SPEED=9600
SERIAL_DEV=ttyS1
if grep -q pontos /etc/hostname; then
    SERIAL_SPEED=115200
    SERIAL_DEV=ttyS0
fi

export LANG=C.UTF-8

cat > /etc/apt/sources.list <<EOF
deb http://ftp.fi.muni.cz/pub/linux/debian/  stable main contrib non-free
deb-src http://ftp.fi.muni.cz/pub/linux/debian/  stable main contrib non-free

deb http://security.debian.org/ stable/updates main contrib non-free
deb-src http://security.debian.org/ stable/updates main contrib non-free
EOF
PATH=/usr/sbin:$PATH
apt update
tasksel install standard
apt install -yy locales ssh initramfs-tools linux-image-amd64 xfsprogs lvm2 \
                vim git ethtool dlocate dhcpcd5
if grep -q pheme /etc/hostname; then
    apt install -yy firmware-bnx2
fi

export DEBCONF_NONINTERACTIVE_SEEN=true DEBIAN_FRONTEND=noninteractive
echo "Europe/Prague" > /etc/timezone
rm -f /etc/localtime || true
dpkg-reconfigure tzdata

# setup network
apt remove -yy ifupdown
cat > /etc/systemd/network/dhcp.network <<EOF
[Match]
Name=en*

[Network]
DHCP=yes
EOF

cat >> /etc/locale.gen <<EOF
cs_CZ.UTF-8 UTF-8
sk_SK.UTF-8 UTF-8
en_US.UTF-8 UTF-8
en_DK.UTF-8 UTF-8
EOF
dpkg-reconfigure locales
update-locale LANG=en_US.UTF-8

if [[ "$2" = "efi" ]]; then
	apt install -yy grub-efi
else
	apt install -yy grub-pc
fi
if ! grep -q 'console serial' /etc/default/grub; then
    sed -i /etc/default/grub -e "s/GRUB_CMDLINE_LINUX_DEFAULT=\"quiet\"/GRUB_CMDLINE_LINUX_DEFAULT=\"quiet console=tty0 console=${SERIAL_DEV},$SERIAL_SPEED\"/"
    cat >> /etc/default/grub <<EOF
# Preload both GPT and MBR modules so that they are not missed
GRUB_PRELOAD_MODULES="part_gpt part_msdos lvm"

## Serial console
GRUB_SERIAL_COMMAND="serial --speed=$SERIAL_SPEED --unit=1"

# Uncomment to use basic console
GRUB_TERMINAL_INPUT="console serial"

# Uncomment to disable graphical terminal
GRUB_TERMINAL_OUTPUT="console serial"
EOF
fi
if [[ "$2" = "efi" ]]; then
	grub-install --target=x86_64-efi --efi-directory=/boot/efi --recheck
else
	grub-install --target=i386-pc $1
fi
update-grub

apt clean

sed -i 's/#\?PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
mkdir -p /root/.ssh
cat <<EOF >> /root/.ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCyTqSTbfhzJUlAV3/WQPefOz/nX0xfGgBbb9mMxwXNm3OKpTLaSJZZ78aUvucCqbiWhWQKCKlUqMsaWCqHLIL5kFDgDRcfGhF8ERCjIG7TCPs1zPPoFVL8hvGeMmWsHgvm8pKjPFCp/NxjTDx3RmLzVyP1z8rLwD3X1xC2bRSETuRwwOIKLEJhzNSQ1EchTNRTH0CuMqVZHdQLVDP6Tdqo7WV61znELRW5ZPw7BPJU216+He7AziIGcLbv06JbuFyFsoZ+8dmH20rs/CwOnicFH/P44yOZmB+JWVzBosKkG8JliM/nzaru7aPPQe/7XIsOQ5iymm31WAK112htIy3N xstill@xstill-lenovo
EOF

echo raid1 >> /etc/initramfs-tools/modules
update-initramfs -u -k all

passwd --delete root

# vim: ft=sh
