#!/usr/bin/env bash

ORIGINAL_USER=$(whoami)
if [[ -n "$SUDO_USER" ]]; then
    ORIGINAL_USER=$SUDO_USER
fi
[[ $UID = 0 ]] || { echo "restarting with sudo" >&2; exec sudo "$0" "$@"; }

set -ex

SELF="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OLDWD=$(pwd)
DIR=$(mktemp -d --tmpdir archiso.XXXXXXXX)
cd $DIR
trap "cd $OLDWD && rm --one-file-system -rf $DIR" EXIT SIGINT SIGQUIT SIGABRT SIGKILL SIGTERM
ARCHISO=/usr/share/archiso
cp -r $ARCHISO/configs/releng archlive
cat >> archlive/packages.x86_64 <<EOF
git
screen
vim
wget
openssh
xfsprogs
arch-install-scripts
strace
lsof
debootstrap
dhcpcd
bind-tools
EOF
echo 'iso_publisher="Vladimír Štill <archiso@vstill.eu>"' >> archlive/profiledef.sh

mkdir -p archlive/airootfs/etc/systemd/system/multi-user.target.wants
for s in sshd dhcpcd; do
    ls -s /usr/lib/systemd/system/$s.service archlive/airootfs/etc/systemd/system/multi-user.target.wants
done
sed -i 's/zsh/bash/' archlive/airootfs/etc/passwd

mkdir archlive/airootfs/root/.ssh
cat > archlive/airootfs/root/.ssh/authorized_keys <<EOF
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDFXnRpFOZQo3E6hK3adOfpRLegp/jwaHqKR+ReiSvl3cPaUhOCVzzP/BGxl115nH+23stXMdy4kUH8j9kzpYTJV0ADqVBz+1lyXD9JIHLQvKVexnvf6Wb26fMmLoOq2Z8PDvYYxMzpZ0L9qKJ6UcdGQyj1rGBGr4otHLC4I8FD/L7Yt4FtRNlMUz4Dj3nGGoz8fdu5iUqtgLZ4Kn25LtoeGY0oIFvUE0zwEtuaUYRbxrTtUsPyJ3pDPjFEKb40TB3dTLhp1Mnujvst40oigIJK6moOJRfQIANDtvJ1P1+XXHs26qoCE5ina5pBCe/Bl5QaPSDaXPgWP7dJAQUDYlh/ xstill@mail.muni.cz
ssh-rsa AA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IddP2HJSPeI0so6bX+Y4U9GOpyfJMyK/3tw/mnvBCQJ/AqvCri2iwBPZqDkVqvibCuuK/HSR3a8DIlTBfuqPK5RWluuapFKsRwueZtJkqxQNdpxpN5/CU4ZSVpj6wowYJK/g6AsvIAOeA+UxzgaI8TZjCDSe3stL0Dawaz5hS90Pg/hHVv8pNBolZzll8= xstill@t14.p.vstill.cz
EOF
sed --in-place '/^file_permissions=(/a   ["/root"]="0:0:0750"\n  ["/root/.ssh"]="0:0:0700"\n  ["/root/.ssh/authorized_keys"]="0:0:0600"' archlive/profiledef.sh
cat archlive/profiledef.sh
echo 'ip link' >> archlive/airootfs/root/.bash_profile

( cd archlive/airootfs/root/ && git clone https://gitlab.fi.muni.cz/paradise/deploy.git )

mkarchiso -v -o . archlive
NAME=$(ls archlinux-*.iso)
cat $NAME | sudo -u $ORIGINAL_USER tee $OLDWD/$NAME >/dev/null

echo "dd bs=4M if=archlinux*.iso of=/dev/some_usb_device status=progress && sync"
