#!/bin/sh

set -e
set -x

ME=$(basename ${0})

CWD=$(pwd)
MYDIR=$(basename ${CWD})
if [ "${MYDIR}" != "live-image" ] ; then
	mkdir -p live-image
	cd live-image
fi

rm -rf auto config local .build chroot cache chroot.files chroot.packages.install chroot.packages.live live-image-amd64.files live-image-amd64.packages binary tftpboot

if ! [ -r /usr/share/openstack-pkg-tools/pkgos_func ] ; then
        echo "Could not read /usr/share/openstack-pkg-tools/pkgos_func."
        exit 1
fi
. /usr/share/openstack-pkg-tools/pkgos_func

supply_gen_ssh_live_key () {
	if ! [ -e /etc/supply-baremetal/id_rsa ] ; then
		ssh-keygen -t rsa -f /etc/supply-baremetal/id_rsa -P ''
	fi
	if ! [ -e /etc/supply-baremetal/authorized_keys ] ; then
		cat /root/.ssh/authorized_keys >/etc/supply-baremetal/authorized_keys
		cat /etc/supply-baremetal/id_rsa.pub >>/etc/supply-baremetal/authorized_keys
	fi
}

supply_find_my_ip () {
	local DEFROUTE_IF DEFROUTE_IP
	DEFROUTE_IF=`awk '{ if ( $2 == "00000000" ) print $1 }' /proc/net/route`
	if [ -n "${DEFROUTE_IF}" ] ; then
		if [ -x /bin/ip ] || [ -x /usr/sbin/ip ] ; then
			DEFROUTE_IP=`LC_ALL=C ip addr show "${DEFROUTE_IF}" | grep inet | head -n 1 | awk '{print $2}' | cut -d/ -f1 | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'`
		else
			DEFROUTE_IP=`hostname -i | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'`
		fi
	fi
	if [ -z "${DEFROUTE_IP}" ] ; then
		echo "Cloud not find out MY_IP."
		exit 1
	else
		MY_IP=${DEFROUTE_IP}
	fi
}

supply_setup_tftp () {
	DEST_TFTP_DIR=/srv/tftp
	if [ -e /usr/lib/shim/shimx64.efi.signed ] ; then
		cp /usr/lib/shim/shimx64.efi.signed ${DEST_TFTP_DIR}
	fi
	if [ -e /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed ] ; then
		cp /usr/lib/grub/x86_64-efi-signed/grubnetx64.efi.signed ${DEST_TFTP_DIR}/grubx64.efi
	fi
	mkdir -p ${DEST_TFTP_DIR}/grub
	echo "set menu_color_normal=white/black
set menu_color_highlight=black/light-gray
set timeout=5

menuentry \"Supply Baremetal\" { 
    linux    vmlinuz boot=live iomem=relaxed console=tty0 console=ttyS0,115200 console=ttyS1,115200 earlyprintk=ttyS1,115200 consoleblank=0 systemd.show_status=true components url=http://${MY_IP}:8088 fetch=http://${MY_IP}:8088/filesystem.squashfs ipa-inspection-callback-url=https://${MY_IP}/inspector/v1/continue ipa-inspection-collectors=default
    initrd   initrd.img
}
" >${DEST_TFTP_DIR}/grub/grub.cfg
}

supply_build_image (){
	mkdir -p config/archives/
	echo "deb http://bookworm-zed.debian.net/debian bookworm-zed-backports main
deb http://bookworm-zed.debian.net/debian bookworm-zed-backports-nochange main
" >config/archives/bookworm-zed.list.chroot
	echo "deb http://bookworm-zed.debian.net/debian bookworm-zed-backports main
deb http://bookworm-zed.debian.net/debian bookworm-zed-backports-nochange main
" >config/archives/bookworm-zed.list.binary
	echo "-----BEGIN PGP PUBLIC KEY BLOCK-----

mQINBGPhFRwBEADDzzzmLdNX0xIkeUsBBYFx6BZkSODNCVOBu1af3MNOqJDr0K76
CyPMnJGveGaw1MrFhb9ui/L1Jn8bKRCPl5i0Yybjgzyaf0mj6PmCar39vqlUThkD
zd9994TRTSdxzkxf1bIHlkN5zuNbMu4S+TCAtEEiv4Rv8FHQ6OuIhPXRZ7GprcFO
P5jZ4I5xj4ZROwySVQpbIRpdu6TnMtjnKFclalPp6lsQ+xzkyQS25PfI6NdfgJXC
mhgXRq/8uJwti44Wwfhn/4zx0yqvDuLXNBXaQyP9/8Hbi3uxIK3CK328+rdomVgm
UEotUfW8ZIEMzeBaamm+fgkfQfDgHlsuyQOF5HETR0hS8p3EogoKPr62P+biVxYU
Nbfy24dBU7M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q2rpy0nrO2t05ogOE0otr9rN
9/nRHpGQABnZaBGlsAWiYnc3LSSYKQWqXYPtBttGdw1XcUBR77BcMyaIG/vPEaTL
7bOIkkN67c6UmKquQlseulj6MenG/Q==
=f2Ie
-----END PGP PUBLIC KEY BLOCK-----" >config/archives/bookworm-zed.key.chroot
	cp config/archives/bookworm-zed.key.chroot config/archives/bookworm-zed.key.binary

	# Add non-free repos
	echo "deb http://mirror.infomaniak.com/debian bookworm contrib non-free non-free-firmware
deb-src http://mirror.infomaniak.com/debian bookworm contrib non-free non-free-firmware
" >config/archives/contrib-non-free.list.chroot
cp config/archives/contrib-non-free.list.chroot config/archives/contrib-non-free.list.binary

	# Customize root and user ~/.screenrc
	mkdir -p config/includes.chroot/root
	echo "startup_message off
defscrollback 5000
caption always \"%{= kw}%-w%{= BW}%n %t%{-}%+w %-= @%H  -  %d.%m.%Y  - %c\"
termcapinfo xterm 'Co#256:AB=\E[48;5;%dm:AF=\E[38;5;%dm'
defbce on
term screen-256color
termcapinfo konsole-256color ti@:te@" >config/includes.chroot/root/.screenrc

	# and /root/.bashrc and /home/user/.bashrc
	echo "# ~/.bashrc: executed by bash(1) for non-login shells.

export LS_OPTIONS='--color=auto'
eval \"\$(dircolors)\"
alias ls='ls \${LS_OPTIONS}'

SYSTEM_SERIAL_NUM=\$(oci-system-serial)

  BLUE=\"\\[\\033[1;34m\\]\"
 LGRAY=\"\\[\\033[0;37m\\]\"
NO_COL=\"\\[\\033[0m\\]\"
 LBLUE=\"\\[\\033[1;36m\\]\"
   RED=\"\\[\\033[1;31m\\]\"

export PS1=\${RED}'\\u'\${LGRAY}@\${BLUE}\${SYSTEM_SERIAL_NUM}\${LGRAY}'>_'\${NO_COL}' \\w # '

alias ssh='ssh -A -X'

if [ -f /etc/bash_completion ]; then
        . /etc/bash_completion
fi

export PAGER=most
" > config/includes.chroot/root/.bashrc

echo "HISTCONTROL=ignoreboth
shopt -s histappend
HISTSIZE=1000
HISTFILESIZE=2000
shopt -s checkwinsize

export LS_OPTIONS='--color=auto'
eval \"\$(dircolors)\"
alias ls='ls \${LS_OPTIONS}'

SYSTEM_SERIAL_NUM=\$(cat /etc/oci/system_serial_num)

  BLUE=\"\\[\\033[1;34m\\]\"
 LGRAY=\"\\[\\033[0;37m\\]\"
NO_COL=\"\\[\\033[0m\\]\"
 LBLUE=\"\\[\\033[1;36m\\]\"
   RED=\"\\[\\033[1;31m\\]\"
 GREEN=\"\\[\\033[1;32m\\]\"
export PS1=\${GREEN}'\\u'\${LGRAY}@\${BLUE}\${SYSTEM_SERIAL_NUM}\${LGRAY}'>_'\${NO_COL}' \\w # '
export PAGER=most
" >config/includes.chroot/root/.bashrc

	mkdir -p config/includes.chroot/root/.ssh
	chmod 700 config/includes.chroot/root/.ssh
	cp /etc/supply-baremetal/authorized_keys config/includes.chroot/root/.ssh
	chmod 600 config/includes.chroot/root/.ssh/authorized_keys

	# Copy the PKI
	mkdir -p config/includes.chroot/usr/share/ca-certificates
	cp -auxf /usr/share/ca-certificates/supply config/includes.chroot/usr/share/ca-certificates/

	###############################
	### Live image package list ###
	###############################
	mkdir -p config/package-lists
	echo "bash-completion
bc
bind9-host
curl
chrony
dmidecode
debootstrap
dosfstools
extlinux
firmware-bnx2
firmware-bnx2x
firmware-linux-free
firmware-misc-nonfree
firmware-qlogic
gnupg2
ipcalc
ipmitool
iproute2
ironic-python-agent
joe
jq
kbd
kpartx
lldpd
less
lshw
lvm2
mbr
mdadm
most
net-tools
nmap
openssh-server
openssh-client
openstack-debian-images
openstack-pkg-tools
parted
pciutils
plymouth
policykit-1
qemu-utils
screen
syslinux-common
tcpdump
util-linux
vim
wget
xfsprogs" > config/package-lists/openstack.list.chroot

	# Add serial console
	mkdir -p config/includes.chroot/etc/systemd/system/getty.target.wants
	echo "#  SPDX-License-Identifier: LGPL-2.1+
#
#  This file is part of systemd.
#
#  systemd 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 2.1 of the License, or
#  (at your option) any later version.

[Unit]
Description=Serial Getty on %I
Documentation=man:agetty(8) man:systemd-getty-generator(8)
Documentation=http://0pointer.de/blog/projects/serial-console.html
BindsTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service plymouth-quit-wait.service getty-pre.target
After=rc-local.service

# If additional gettys are spawned during boot then we should make
# sure that this is synchronized before getty.target, even though
# getty.target didn't actually pull it in.
Before=getty.target
IgnoreOnIsolate=yes

# IgnoreOnIsolate causes issues with sulogin, if someone isolates
# rescue.target or starts rescue.service from multi-user.target or
# graphical.target.
Conflicts=rescue.service
Before=rescue.service

[Service]
# The '-o' option value tells agetty to replace 'login' arguments with an
# option to preserve environment (-p), followed by '--' for safety, and then
# the entered username.
ExecStart=-/sbin/agetty --autologin root --keep-baud 9600 %I \$TERM
Type=idle
Restart=always
UtmpIdentifier=%I
TTYPath=/dev/%I
TTYReset=yes
TTYVHangup=yes
KillMode=process
IgnoreSIGPIPE=no
SendSIGHUP=yes

[Install]
WantedBy=getty.target
" >config/includes.chroot/etc/systemd/system/serial-getty@ttyS1.service
	cp config/includes.chroot/etc/systemd/system/serial-getty@ttyS1.service config/includes.chroot/etc/systemd/system/serial-getty@ttyS0.service
	ln -s ../serial-getty@ttyS1.service config/includes.chroot/etc/systemd/system/getty.target.wants/serial-getty@ttyS1.service
	ln -s ../serial-getty@ttyS0.service config/includes.chroot/etc/systemd/system/getty.target.wants/serial-getty@ttyS0.service

	# Configure autologin for tty0
	mkdir -p config/includes.chroot/etc/systemd/system/getty@.service.d
	echo "[Service]\nExecStart=\nExecStart=-/sbin/agetty --autologin root --noclear %I \$TERM" >config/includes.chroot/etc/systemd/system/getty@.service.d/root-autologin.conf

	lb clean
	lb config --mirror-binary http://mirror.infomaniak.com/debian -b netboot --bootappend-live "boot=live iomem=relaxed console=tty0 console=ttyS0,115200 console=ttyS1,115200 earlyprintk=ttyS1,115200 consoleblank=0 systemd.show_status=true components url=http://${MY_IP} fetch=http://${MY_IP}:8088/filesystem.squashfs" --net-root-path /srv/tftp --net-root-server ${MY_IP}
	for i in LB_PARENT_MIRROR_BOOTSTRAP LB_PARENT_MIRROR_CHROOT LB_PARENT_MIRROR_DEBIAN_INSTALLER LB_MIRROR_BOOTSTRAP LB_MIRROR_CHROOT LB_MIRROR_DEBIAN_INSTALLER LB_PARENT_MIRROR_BINARY LB_MIRROR_BINARY ; do
		sed -i 's|^'${i}'=.*|'${i}'="'http://mirror.infomaniak.com/debian'"|' config/bootstrap
	done
	for i in LB_PARENT_MIRROR_CHROOT_SECURITY LB_PARENT_MIRROR_BINARY_SECURITY LB_MIRROR_CHROOT_SECURITY LB_MIRROR_BINARY_SECURITY ; do
		sed -i 's|^'${i}'=.*|'${i}'="'http://mirror.infomaniak.com/debian-security/'"|' config/bootstrap
	done

	sed -i 's/^LB_BOOTLOADERS=.*/LB_BOOTLOADERS="syslinux"/' config/binary

	# Fix the default syslinux timeout to 20 seconds
#	sed -i "s/timeout 0/timeout 20/" config/bootloaders/isolinux/isolinux.cfg
#	sed -i "s/timeout 0/timeout 20/" config/bootloaders/pxelinux/pxelinux.cfg/default
#	sed -i "s/timeout 0/timeout 20/" config/bootloaders/syslinux/syslinux.cfg
#	sed -i "s/timeout 0/timeout 20/" config/bootloaders/extlinux/extlinux.conf
#
	sed -i s/ftp.debian.org/mirror.infomaniak.com/ config/bootstrap

	debian_release=bookworm

	# Customize the distribution name
	sed -i "s#LB_DEBIAN_INSTALLER_DISTRIBUTION=.*#LB_DEBIAN_INSTALLER_DISTRIBUTION=\"${debian_release}\"#" config/binary
	sed -i "s#LB_ISO_VOLUME=.*#LB_ISO_VOLUME=\"Debian ${debian_release} \$(date +%Y%m%d-%H:%M)\"#" config/binary
	if [ -e config/build ] ; then
		sed -i "s#Distribution: .*#Distribution: ${debian_release}#" config/build
	fi
	sed -i "s#LB_DISTRIBUTION=.*#LB_DISTRIBUTION=\"${debian_release}\"#" config/bootstrap
	sed -i "s#LB_PARENT_DISTRIBUTION=.*#LB_PARENT_DISTRIBUTION=\"${debian_release}\"#" config/bootstrap
	sed -i "s#LB_PARENT_DEBIAN_INSTALLER_DISTRIBUTION=.*#LB_PARENT_DEBIAN_INSTALLER_DISTRIBUTION=\"${debian_release}\"#" config/bootstrap

	# New names to tweak starting with Bullseye
	sed -i "s#LB_DISTRIBUTION_CHROOT=.*#LB_DISTRIBUTION_CHROOT=\"${debian_release}\"#" config/bootstrap
	sed -i "s#LB_PARENT_DISTRIBUTION_CHROOT=.*#LB_PARENT_DISTRIBUTION_CHROOT=\"${debian_release}\"#" config/bootstrap
	sed -i "s#LB_DISTRIBUTION_BINARY=.*#LB_DISTRIBUTION_BINARY=\"${debian_release}\"#" config/bootstrap
	sed -i "s#LB_PARENT_DISTRIBUTION_BINARY=.*#LB_PARENT_DISTRIBUTION_BINARY=\"${debian_release}\"#" config/bootstrap

	lb build

	cp binary/live/filesystem.squashfs /srv/tftp
	cp -r tftpboot/* /srv/tftp
	cp -auxf tftpboot/live/vmlinuz* /srv/tftp
	cp -auxf tftpboot/live/vmlinuz* tftpboot/live/initrd* /srv/tftp
}

supply_find_my_ip
supply_setup_tftp
supply_build_image

cd ${CWD}
