#!/usr/bin/env bash

# Once you have run this script you should be able to
#
# drive names must be changed in blends/devuan-desktop-metal/config
# blends/devuan-desktop-metal/daedalus/config has the installed package list
#
# then:
# $ cd /var/tmp/live-sdk
# $ tmuxp load .
#
# This will give you two frames, one in the live-sdk env and one not.
# Use ^B arrow to switch between them,
#
# To install run:
# $ build_metal_dist

# This script is intended to be run of an sdcard live image NOT a running system.
#
# It copies /var/tmp/live-sdk from 192.168.1.102 if the ssh key exchange does not
# fix password requests the default:default can be used.
#
# It takes the blends/devuan-desktop-live directory as a template and copies the
# configuration files in live-metal to the newly named blend directory.
#
# The sources.list will be updated to a snapshot.debian.org date that matches
# the live sdcard release (bookworm) if you change the live sdcard image you
# must change the date of the snapshot.

# check for the availability of color terminfoi, fix it if it's missing.
if [[ ! -f /lib/terminfo/t/tmux-256color ]]; then
	wget -c https://raw.githubusercontent.com/jez/dotfiles/master/tmux-256color.terminfo
	tic ./tmux-256color.terminfo
fi

# Fix "cannot allocate memory"
echo 1 >/proc/sys/kernel/sysrq
echo f >/proc/sysrq-trigger
echo 0 >/proc/sys/kernel/sysrq

# Make a swap device that will allow apt to update and install.
dd if=/dev/zero bs=1M of=/swapfile count=128
chmod 0600 /swapfile
mkfs.ext2 /swapfile
mount -o loop /swapfile /mnt
dd if=/dev/zero bs=1M of=/mnt/swap
mkswap /mnt/swap
chmod 0600 /mnt/swap
swapon /mnt/swap

rm /etc/apt/sources.list.d/mkusb-ppa.list
rm /etc/apt/sources.list.d/yarn.list
rm /etc/apt/sources.list.d/docker.list
rm /etc/apt/sources.list.d/brave-browser.list
rm /etc/apt/sources.list.d/nodesource.list
rm /etc/apt/sources.list.d/matrix-riot-im.list

# the snapshot.debian.org sources.list for the sdcard image.
# rm /etc/apt/sources.list

# To reduce the number of packages installed with an update we put a fixed date
# sources.list from snapshot.debian.org that matches the release of the live sdcard.

# jessie caused a name collision with debian, capitalized ascii is already used
# for something and just an anoying choice, they calmed down after that
# (or someone left).

# 		                corresponds to Debian 7     Wheezy		20170617T034212Z
# Devuan 1.0 Jessie     corresponds to Debian 8     Jessie		20180623T023722Z
# Devuan 2.0 ASCII      corresponds to Debian 9     Stretch		20200717T204551Z
# Devuan 3.0 Beowulf    corresponds to Debian 10.4  Buster		20230611T103552Z
# Devuan 4.0 Chimaera   corresponds to Debian 11.1  Bullseye	20230611T103552Z
# Devuan 5.0 Daedalus   corresponds to Debian 12    Bookworm	20231007T150030Z
# Devuan 6.0 Excalibur  corresponds to Debian 13    Trixie		testing
# Devuan 7.0 Freia      corresponds to Debian 14    Forky
# Devuan     Ceres      corresponds to Debian       Sid			unstable

RELEASE_NAME=bookworm
SOURCES_DATE=20221017T031443Z
SNAPSHOT_SERVER="snapshot.debian.org"
# SNAPSHOT_SERVER="snapshot.notset.fr"
cat <<-EOF | sudo tee /etc/apt/sources.list.d/snapshot.sources.list
	deb     https://"${SNAPSHOT_SERVER}"/archive/debian/"${SOURCES_DATE}"/ "${RELEASE_NAME}" main contrib non-free non-free-firmware
	deb-src https://"${SNAPSHOT_SERVER}"/archive/debian/"${SOURCES_DATE}"/ "${RELEASE_NAME}" main contrib non-free non-free-firmware
	deb     https://"${SNAPSHOT_SERVER}"/archive/debian-security/"${SOURCES_DATE}"/ "${RELEASE_NAME}"-security main contrib non-free non-free-firmware
	deb-src https://"${SNAPSHOT_SERVER}"/archive/debian-security/"${SOURCES_DATE}"/ "${RELEASE_NAME}"-security main contrib non-free non-free-firmware
EOF
# cp ./snapshot.sources.list /etc/apt/sources.list.d/snapshot.sources.list

# Update apt even if upstream have shifted to a new release.
echo 'Acquire::Check-Valid-Until "false";' | sudo tee /etc/apt/apt.conf.d/99validuntil
echo 'Acquire::AllowReleaseInfoChange::Suite "true";' | sudo tee /etc/apt/apt.conf.d/99releaseinfochange
echo 'APT::Get::AllowUnauthenticated "true";' | sudo tee -a /etc/apt/apt.conf.d/99unauth
echo 'quiet::ReleaseInfoChange::Version "true";' | sudo tee -a /etc/apt/apt.conf.d/99releaseinfochange

# When a suite gets advanced from testing to stable the release info changes,
# allow to update without error.
apt-get update --allow-releaseinfo-change -y

# Keep the existing kernel and headers to prevent multiple builds of the zfs
# module for additional kernels.
KERNEL_VERSION="$(uname -r)"
apt-mark hold \
	linux-image-"${KERNEL_VERSION}" \
	linux-headers-"${KERNEL_VERSION}" \
	linux-image-amd64 \
	linux-headers-amd64
apt-get install linux-headers-"${KERNEL_VERSION}" zfs-dkms

modprobe zfs

# Remove libreoffice, updating an installed libreoffice is time consuming and
# uses a lot of disk space on an sdcard image.
apt-get remove -y --purge \
	libreoffice \
	libreoffice-common \
	libreoffice-calc \
	libreoffice-core \
	libreoffice-writer \
	libreoffice-impress \
	libreoffice-draw \
	libreoffice-math \
	libreoffice-base \
	libreoffice-gtk3 \
	liblibreoffice-java \
	libreoffice-sdbc-hsqldb \
	libreoffice-base-drivers
apt-get -y autoremove
apt-get install -y lsof jc jq gdisk hdparm debootstrap dosfstools rsync \
	openssh-server sshpass eudev # desktop-base

apt-get clean

# install server public key for ssh from ~/.ssh/id_rsa.pub
mkdir -p ~/.ssh && cat ./sistarte-id_rsa.pub >>"${HOME}"/.ssh/authorized_keys

#
# Exchange ssh keys
AUTOMATE_IP="192.168.1.102"
LOCAL_USER_EMAIL="devuan@${AUTOMATE_IP}"
ssh-keygen -t rsa -b 4096 -N '' -C "${LOCAL_USER_EMAIL}" -f "${HOME}"/.ssh/id_rsa
sshpass -f sistarte_password.txt ssh-copy-id default@${AUTOMATE_IP}

#git clone https://git.devuan.org/devuan-sdk/live-sdk ../live-sdk
#cd ../livecd || exit; git submodule update --init --recursive --checkout
alias ssh="ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null"

# rsync -ratlz \
#	--rsh="/usr/bin/sshpass -p password ssh -l username" \
#	src_path  \
#	dest_path

rsync -avz \
	--exclude='.git/*' \
	--exclude='*gz' \
	--exclude='*deb' \
	-e ssh default@"${AUTOMATE_IP}":/var/tmp/automate \
	../

# git clone ssh://git@git2.ring-zero.co.uk/scripts/automate.git ../automate

ln -sf ../automate /var/tmp/automate

bash ../automate/010_generate-ssh.sh "${HOME}"
bash ../automate/001_ssh.sh

# SDCARD_ID="usb-Mass_Storage_Device_121220160204-0:0-part1"
# mkdir -p ../live-sdk
# if ! mountpoint -q ../live-sdk; then
# 	fsck.ext4 -f /dev/disk/by-id/${SDCARD_ID}
# 	mount /dev/disk/by-id/${SDCARD_ID} ../live-sdk
# else
# 	echo "mount point already in use, skipping mount operation."
# fi

rsync -avz \
	--exclude='.git' \
	--exclude='tmp/*' \
	--exclude='dist/*' \
	--exclude='git/*' \
	-e ssh default@${AUTOMATE_IP}:/var/tmp/live-sdk \
	../live-sdk

# git clone https://git.devuan.org/devuan-sdk/live-sdk ../live-sdk
# git clone https://git2.ring-zero.co.uk/devuan-sdk/live-sdk.git ../live-sdk

mkdir -p ../live-sdk/log
mkdir -p ../live-sdk/tmp

# Uncomment to speed up subsequent builds
# rsync -avz \
# 	-e ssh default@${AUTOMATE_IP}:/var/tmp/"bootstrap-devuan-amd64-stage*.cpio.gz" \
# 	/var/tmp/live-sdk/tmp/

# Install
# metal install chimaera (bare metal install to zfs following openzfs zfs rootfs)
RELEASE_NAME="daedalus"
BLEND_NAME=devuan-desktop-metal
TEMPLATE=devuan-desktop-live
sed -i \
	"/blend_map=.*/ s/.*/&\n\t\t\"${BLEND_NAME}\"  \"\$R\/blends\/${BLEND_NAME}\/${BLEND_NAME}.blend\"/" \
	../live-sdk/sdk

mkdir -p ../live-sdk/blends/${BLEND_NAME}/${RELEASE_NAME}
cp -a ../live-sdk/blends/${TEMPLATE} ../live-sdk/blends/${BLEND_NAME}
cp blend_config ../live-sdk/blends/${BLEND_NAME}/config
cp blend_${RELEASE_NAME}_config ../live-sdk/blends/${BLEND_NAME}/${RELEASE_NAME}/config
cp blend_sysconf ../live-sdk/blends/${BLEND_NAME}/sysconf
cp blend_sysconf.md ../live-sdk/blends/${BLEND_NAME}/sysconf.md
cp blend_helpers ../live-sdk/blends/${BLEND_NAME}/helpers
cp blend_helpers.md ../live-sdk/blends/${BLEND_NAME}/helpers.md
cp devuan-desktop-metal.blend ../live-sdk/blends/${BLEND_NAME}/
cp devuan-desktop-metal.md ../live-sdk/blends/${BLEND_NAME}/
cp console_livesdk.sh ../live-sdk/
cp dot_tmuxp_metal.yaml ../live-sdk/.tmuxp.yaml

# docker image minimal (following debuerreotype methods)
BLEND_NAME=devuan-minimal-docker
TEMPLATE=devuan-minimal-live
sed -i \
	"/blend_map=.*/ s/.*/&\n\t\t\"${BLEND_NAME}\"  \"\$R\/blends\/${BLEND_NAME}\/${BLEND_NAME}.blend\"/" \
	../live-sdk/sdk

mkdir -p ../live-sdk/blends/${BLEND_NAME}/${RELEASE_NAME}
cp -a ../live-sdk/blends/${TEMPLATE} ../live-sdk/blends/${BLEND_NAME}
cp blend_${RELEASE_NAME}-docker_config ../live-sdk/blends/${BLEND_NAME}/${RELEASE_NAME}/config
cp blend_config-docker ../live-sdk/blends/${BLEND_NAME}/config-docker
cp blend_sysconf ../live-sdk/blends/${BLEND_NAME}/sysconf
cp blend_sysconf.md ../live-sdk/blends/${BLEND_NAME}/sysconf.md
cp blend_helpers-docker ../live-sdk/blends/${BLEND_NAME}/helpers-docker
cp blend_helpers-docker.md ../live-sdk/blends/${BLEND_NAME}/helpers-docker.md
cp devuan-minimal-docker.blend ../live-sdk/blends/${BLEND_NAME}/
cp devuan-minimal-docker.md ../live-sdk/blends/${BLEND_NAME}/
cp tar-excludes ../live-sdk/blends/${BLEND_NAME}/

# ln -sf ${RELEASE_NAME}.config config

bash ../automate/010_zram.sh && /etc/init.d/zram start
bash ../automate/020_tmux.sh "${HOME}"
bash ../automate/020_zsh_quickstart.sh "${HOME}"

sudo -i -u devuan '/usr/share/tmux-plugin-manager/bin/install_plugins'
sudo -i '/usr/share/tmux-plugin-manager/bin/install_plugins'

ps aux >../live-sdk/log/psaux.pre
lsof >../live-sdk/log/lsof.pre

# Fix the innumeration of drives to usbe ata-* rather than wwn-*

# could import from blend_config
# disk_path="/dev/disk/by-id"
# disk_name="ata-CT1000MX500SSD1_2321E6DBE216"
# disk2_name="ata-CT1000MX500SSD1_2321E6DBE1D2"
#
# raid=mirror
#
# available_disks=("${disk_name}")
# if [[ -v $raid ]]; then
# 	available_disks+="${disk2_name}"
# fi

# source blend_config
# for disk in "${available_disks[@]}"; do
# 	TARGET="/dev/disk/by-id/${disk}"
#
# 	UDEV_OUTPUT=$(udevadm info --query=all "${TARGET}" | jc --udevadm -p | jq 'del(.E.ID_MODEL_ENC)')
# 	MODEL=$(echo -n "${UDEV_OUTPUT}" | jq -r '.E.ID_MODEL')
# 	SERIAL=$(echo -n "${UDEV_OUTPUT}" | jq -r '.E.ID_SERIAL_SHORT')
# 	echo "SUBSYSTEM==\"block\", \
# 		ATTRS{model}=\"$MODEL\", \
# 		ATTRS{serial_short}=\"$SERIAL\", \
# 		SYMLINK+=\"disk/by-id/ata-\$attr{serial_short}\"" | \
# 		sudo tee /etc/udev/rules.d/99-custom-ata-names.rules
# done

# udevadm control --reload-rules && sudo udevadm trigger
