#!/bin/bash -ex

#----------------------------------------------------------------------------
# DARKNESS RASPBERRYPI QUASI-INSTALLER - (c) Nikolaus Klepp office@klepp.biz
#----------------------------------------------------------------------------
# This program take the latest DEVUAN EXCALIBUR arm-build, upgrades to CERES
# installs TDE and injects DARKNESS customisations. Locales/language settings
# are taken from your working environment.
# Please note: this is intended to be used from inside a DARKNESS LIVE ISO,
# especially the custumisations. Whem you use it from a different environment
# you will lose these customisatione ('cause I did not package them ... yet)
#----------------------------------------------------------------------------
# 2026-05-16 : initial release
#----------------------------------------------------------------------------

# will most likely only work as root
if [ $UID != 0 ]; then
    echo "you need to be root for this to work."
    exit 1
fi


# For which Raspberrypi do we want the image:
# 4 : RPI 4 / 400 and up
# 5 : RPI 5 and up
RPI=4


# source of devuan base image
URL=https://arm-files.devuan.org/RaspberryPi%20Latest%20Builds/


# Usage ...
if [ $# -ne 1 ]; then
    echo "Usage:  $(basename $0) TARGET"
    echo "TARGET must be either a disk or file but not a partition."
    exit 1
fi


# Sanitycheck - in case you are trying to target a mounted drive
if [ -f "$1" ]; then
    IMG="$1"
    DEV=/dev/loop0
    PART=${DEV}p
    losetup -D || exit 1
else
    if [ -z "$(lsblk $1 | grep ' disk')" ]; then
        echo "ERROR: $1 is not a disc."
        exit 1
    fi
    if [ 0 -lt $(mount|grep "$1"|wc -l) ]; then
        mount | grep "$1"
        echo "ERROR: $1 or one of its partitions is in use."
        exit 1
    fi
    IMG=
    DEV="$1"
    PART=$(echo "$DEV"|sed 's#\(/[^sh][^/]*\)$#\1p#')
fi

# Check, if target device is a block device and present
if [ ! -b "$DEV" ]; then
    echo \"$DEV\" not present.
    exit 1
fi




# qemu is needed for in-image work - this should go into the package
# dependencies when it'll be packaged some day
apt -y update
for i in qemu-system qemu-user-binfmt debootstrap; do
    dpkg -l $i >/dev/null 2>&1 || apt -y install $i
done
apt-get clean


# emulation activated?
if [ ! -e /proc/sys/fs/binfmt_misc/register ]; then
    mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc
fi
if [ ! -e /proc/sys/fs/binfmt_misc/qemu-aarch64 ]; then
    cat /usr/lib/binfmt.d/qemu-aarch64.conf > /proc/sys/fs/binfmt_misc/register
fi


# get the image zip-file
ZIP=$(curl --silent $URL | tr -d '\n' | tr '<>' '\n' | sed -n 's/^a href="\(.*\.zip\)"/\1/p' |\
      grep excalibur | grep arm64 | grep ^rpi-$RPI | sort -n -r | head -n 1)
SHA256SUM=$(curl --silent $URL/$ZIP.sha256sum | cut -d ' ' -f 1)


# only reload, when file is not present
if [ ! -f "$ZIP" ]; then
	wget "$URL/$ZIP"
fi


# check if checksum matches
if [ "$(sha256sum $ZIP | cut -d ' ' -f 1)" != "$SHA256SUM" ]; then
	echo "error: checksum does not match."
	rm "$ZIP"
	exit 1
fi


# name of img inside the zip archive
SRC=$(unzip -l "$ZIP"|awk '/\.img$/ {print $4}')


# file target need special treating ...
if [ -n "$IMG" ]; then
    losetup -D
    sleep 1
	truncate -s 8G $IMG
	# copy source image
	unzip -p "$ZIP" "$SRC" | dd conv=notrunc of="$IMG" bs=100M
	sfdisk $IMG  << XXX
$(sfdisk -d $IMG | sed 's#\(size=\) *[0-9]*\(, *type=83\)#\1 \2#')
XXX
    losetup $DEV "$IMG" --partscan
else
	# copy source image
	unzip -p "$ZIP" "$SRC" | dd of="$DEV" bs=100M
	sfdisk $DEV  << XXX
$(sfdisk -d $DEV | sed 's#\(size=\) *[0-9]*\(, *type=83\)#\1 \2#')
XXX
fi


# automounter fun ...
sleep 5
if [ -n "$(mount|grep $PART)" ]; then
    for i in $(mount|grep $PART|awk '{print $1}'|sort -r); do
        umount $i
    done
fi


# resize root partition
e2fsck    -f ${PART}2
resize2fs -f ${PART}2


# Mount targets ...
MNT=/tmp/rpi
mkdir -p $MNT
mount ${PART}2 $MNT
mount ${PART}1 $MNT/boot/broadcom


# prepare chroot environment
mount x $MNT/proc    -t proc
mount x $MNT/sys     -t sysfs
mount x $MNT/tmp     -t tmpfs
mount x $MNT/dev     -t devtmpfs
mount x $MNT/dev/pts -t devpts


# Now we are set for cdroot and other modifications

# frontend for deb/apt/etc.
export DEBIAN_FRONTEND=noninteractive

# Locales & keyboard
cp /etc/default/keyboard $MNT/etc/default/keyboard
cp /etc/locale.gen       $MNT/etc/locale.gen
cp /etc/locale.conf      $MNT/etc/locale.conf
cp /etc/default/locale   $MNT/etc/default/locale
cp ~/.bashrc             $MNT/root
chroot $MNT locale-gen
chroot $MNT update-locale LANG=$LANG LANGUAGE=\"$LANGUAGE\"

chroot $MNT dpkg-reconfigure keyboard-configuration
chroot $MNT dpkg-reconfigure console-setup


# upgrade to devuan ceres and install vulnerability mitigations
cat > $MNT/etc/apt/sources.list.d/devuan.sources << XXX
Types: deb
URIs: http://deb.devuan.org/merged
Suites: ceres
Components: main contrib non-free non-free-firmware
Enabled: yes
Signed-By: /usr/share/keyrings/devuan-archive-keyring.gpg
XXX
chroot $MNT apt update
chroot $MNT apt -o Dpkg::Options::="--force-confnew" --assume-yes install linux-vulnerability-mitigation
chroot $MNT apt -o Dpkg::Options::="--force-confnew" --assume-yes dist-upgrade


# add TDE sources and install TDE
cat > $MNT/etc/apt/sources.list.d/trinity.sources << XXX
Types: deb
URIs: http://mirror.ppa.trinitydesktop.org/trinity-testing
Suites: ceres
Components: main deps extra
Enabled: yes
Signed-By: /etc/apt/trusted.gpg.d/trinity-archive-keyring.gpg
XXX
chroot $MNT wget https://mirror.ppa.trinitydesktop.org/trinity/deb/trinity-keyring.deb
chroot $MNT dpkg -i trinity-keyring.deb
chroot $MNT rm trinity-keyring.deb
chroot $MNT apt update
chroot $MNT apt --assume-yes install joe openscad $(apt-mark showmanual | grep '\(trinity\|network\)')


# DARKNESS sources and install tweaks
KEY=$(curl https://darkness.klepp.cn/devuan/pool/main/ --silent | tr '"' '\n' | grep '^darkness-key.*.deb$')
chroot $MNT wget https://darkness.klepp.cn/devuan/pool/main/$KEY
chroot $MNT dpkg -i $KEY
chroot $MNT rm $KEY
chroot $MNT apt update
chroot $MNT apt --assume-yes install $(apt-mark showmanual | grep darkness)

# final upgrade
chroot $MNT apt --assume-yes dist-upgrade
chroot $MNT apt --assume-yes autoremove



# THIS SHOULD GO INTO PACKAGE darkness-tweaks !!!!
rsync -av --delete /etc/skel/ $MNT/etc/skel/
cp /usr/local/sbin/adduser.local         $MNT/usr/local/sbin/adduser.local
cp /etc/udev/rules.d/99-udisks2.rules    $MNT/etc/udev/rules.d/99-udisks2.rules
# OpenSCAD colorscheme is missing !!!
#cp /etc/trinity/kateschemarc             $MNT/etc/trinity/kateschemarc
#cp /etc/trinity/katesyntaxhighlightingrc $MNT/etc/trinity/katesyntaxhighlightingrc


# hide /dev/mmcblk*
cat > $MNT/etc/skel/.trinity/share/config/media_panelapplet_v5ux95uxdi4d7yhqgba2_rc << XXX
[General]
ExcludedMedia=media:/mmcblk0p1;media:/mmcblk0p2
ExcludedTypes=media/hdd_mounted;media/nfs_mounted;media/smb_mounted;media/hdd_unmounted;media/nfs_unmounted;media/smb_unmounted
XXX


# move/rename "devuan" user to "user" and fill it from skeleton
mv $MNT/home/devuan $MNT/home/user
sed -i 's#devuan#user#g' $MNT/etc/*shadow* $MNT/etc/*passwd* $MNT/etc/*group*
chroot $MNT passwd -s user << XXX
user
user
XXX


# Fill devuan user
rsync -av --delete /etc/skel/ $MNT/home/devuan/
rm $MNT/etc/skel/Desktop/refractainstaller.desktop
rsync -av --delete $MNT/etc/skel/ $MNT/home/user/


# make it autologin
sed -i 's/^#\(AutoLoginAgain\)=.*$/\1=true/'   $MNT/etc/trinity/tdm/tdmrc
sed -i 's/^#\(AutoLoginDelay\)=.*$/\1=0/'      $MNT/etc/trinity/tdm/tdmrc
sed -i 's/^#\(AutoLoginEnable\)=.*$/\1=true/'  $MNT/etc/trinity/tdm/tdmrc
sed -i 's/^#\(AutoLoginLocked\)=.*$/\1=false/' $MNT/etc/trinity/tdm/tdmrc
sed -i 's/^#\(AutoLoginUser\)=.*$/\1=user/'    $MNT/etc/trinity/tdm/tdmrc

# manually ensure it's installed
export DEBIAN_FRONTEND=
chroot $MNT dpkg-reconfigure linux-vulnerability-mitigation

# unmount target
umount $MNT/dev/pts
umount $MNT/dev
umount $MNT/tmp
umount $MNT/sys
umount $MNT/proc

sync
umount $MNT/boot/broadcom
umount $MNT
rmdir  $MNT

if [ -n "$IMG" ]; then
    losetup -D
fi

