#!/bin/bash
set -euo pipefail #strict mode

# Debian Linux setup script for the XFCE desktop
# Frank ENDRES, (first at last dot fr) - 2024-02
# Licence: [CeCILL](https://cecill.info/licences/Licence_CeCILL_V2.1-en.txt)
# Version: 2026.04.11


echo -e "\nCheck prerequisites…"
if [ $(id -u) != 0 ]; then
	echo "error: $(basename $0) must be run as root"
	exit 1
fi
sysroot=${1:-"system"}; sysroot=${sysroot%/} #remove trailing slash
if [ -z "$sysroot" ]; then
	echo "error: destination can't be '/'"
	exit 2
fi
missing=false
for command in wget; do
	if [ -z "$(which $command 2>/dev/null)" ]; then
		echo "error: missing command $command"
		missing=true
	fi
done
if $missing; then exit 3; fi


echo -e "\nConfiguration:"
HOSTNAME=${HOSTNAME:-linomad}
USERNAME=${USERNAME:-linomad}
PASSWORD=${PASSWORD:-linomad}

#LC (locale), FF (firefox), TB (thunderbird), LO (libreoffice), HS (hunspell) and TA (tesseract)
LC_I18N=${LC_I18N:-"fr_FR de_DE es_ES it_IT pt_PT en_US"} #for locale-gen (ar_EG bn_BD hi_IN ja_JP ru_RU zh_CN)
#FF_I18N=${FF_I18N:-"fr de es-es it pt-pt"}   #FireFox (ar bn hi-in ja ru zh-cn)
#TB_I18N=${TB_I18N:-"fr de es-es it pt-pt"}   #ThunderBird (ar ja ru zh-cn)
#LO_I18N=${LO_I18N:-"fr de es it pt"} #LibreOffice (ar bn hi ja ru zh-cn)
#HS_I18N=${HS_I18N:-"fr de en_us es_any it"}   #HunSpell (ru) - required by LibreOffice / Thunderbird
#TA_I18N=${TA_I18N:-"fra deu eng spa ita por"} #TesserAct ( ara ben hin jpn rus chi_sim)
LANG=${LANG:-fr}
#KEYMAP=$(localectl status | grep "VC Keymap" | cut -c16- | cut -f1 -d' ') #requires SystemD
#KEYMAP=$(localectl status | grep "X11 Layout" | cut -c16- | cut -f1 -d' ') #requires SystemD
KEYMAP=${KEYMAP:-${LANG:0:2}}
TIMEZONE=${TIMEZONE:-$(readlink /etc/localtime | cut -f5- -d/)}
echo -e "\tHOSTNAME = $HOSTNAME\n\tUSERNAME = $USERNAME\n\tPASSWORD = $PASSWORD" \
		"\n\tLOCALES = $LC_I18N\n\tLANGUAGE = $LANG\n\tKEYMAP = $KEYMAP\n\tTIMEZONE = $TIMEZONE"


echo -e "\nSource and destination:"
#~ MIRROR=${MIRROR:-'https://geo.mirror.pkgbuild.com'} - USE DEFAULT
LINOMAD=${LINOMAD:-"packages"}; LINOMAD=${LINOMAD%/} #remove trailing slash
#~ echo -e "\tMIRROR = $MIRROR"
echo -e "\tLINOMAD = $LINOMAD/"
if [ -z "$sysroot" ]; then echo -e "\n\tdestination = /"; else echo -e "\n\tdestination = $sysroot/"; fi

echo -en "\nContinue [y/N]? "; read resp
if [ "$resp" != "Y" ] && [ "$resp" != "y" ]; then echo -e "\nAborting installation."; exit; fi


if [ ! -d $LINOMAD/ ]; then
	echo -e "\nSync LiNomad packages…"
	wget -nv -r -np -nH --cut-dirs=3 --reject "index.html*" -P $LINOMAD/ https://fox-echo.info/linomad/res/pkg/debian/ \
		2>&1 | grep ".deb\"" | sed -e 's/^.* -> "\([^"]*\)".*$/\1/' -e s@$LINOMAD/debian@$LINOMAD@
	mv $LINOMAD/debian/* $LINOMAD/; rmdir $LINOMAD/debian
	echo ""
fi


if [ ! -f rootfs.tar.gz ]; then
	echo -e "\nDownload bootstrap image…"
	wget https://github.com/debuerreotype/docker-debian-artifacts/raw/dist-amd64/testing/oci/blobs/rootfs.tar.gz #stable
fi

echo -e "\nExtracting bootstrap image…"
mkdir -p $sysroot
tar xf rootfs.tar.gz -C $sysroot --numeric-owner 2>/dev/null

echo -e "\nConfiguring package manager…"
mount -t proc /proc $sysroot/proc/
mount --make-rslave --rbind /dev $sysroot/dev
mount --make-rslave --rbind /sys $sysroot/sys
#~ MIRROR
sed 's/^Components: main.*/Components: main contrib non-free non-free-firmware/' -i $sysroot/etc/apt/sources.list.d/debian.sources
chroot $sysroot apt update
chroot $sysroot apt -y upgrade

mkdir $sysroot/packages
mount --bind $LINOMAD/ $sysroot/packages/


#base packages:
packages=""
packages="$packages linux-base linux-image-amd64 firmware-linux-free firmware-linux-nonfree firmware-misc-nonfree initramfs-tools grub-efi-amd64 efibootmgr os-prober"
packages="$packages kbd iproute2 iputils-ping nftables dosfstools exfatprogs fscrypt cryfs f2fs-tools" #encfs(was in Trixie, Linux/encfs ←sync→ Android/EDS-Lite)
packages="$packages man-db less sudo gnu-which vis lua-lpeg tree unzip nano inotify-tools locales dialog"
packages="$packages curl wget rsync openssh-client"
packages="$packages squashfs-tools xorriso gdisk" #live-system / LiNomad

#driver packages:
packages="$packages power-profiles-daemon" #tlp
packages="$packages wireplumber pipewire-pulse pipewire-jack"
packages="$packages iwd network-manager network-manager-openvpn wireguard-tools network-manager-iwd openvpn-systemd-resolved"
packages="$packages mesa-libgallium mesa-vulkan-drivers intel-media-va-driver i965-va-driver vainfo" #video acceleration (mesa-va-drivers)
packages="$packages vdpauinfo" #(libvdpau-va-gl1 libvpl2 vulkan-tools)
packages="$packages cups printer-driver-cups-pdf sane-airscan libnss-mdns" #driverless printing and scanning

#desktop packages:
packages="$packages xorg xdg-utils xdg-user-dirs xdg-desktop-portal-gtk"
packages="$packages lightdm-gtk-greeter lightdm-gtk-greeter-settings light-locker dconf-editor dconf-cli"
#packages="$packages qt6ct"
packages="$packages xfce4-session xfwm4 labwc xfce4-panel xfdesktop4 xfce4-notifyd xfconf-gsettings-backend"
packages="$packages xfce4-power-manager xfce4-settings xfce4-screensaver xfce4-screenshooter xfce4-taskmanager"
packages="$packages xfce4-xkb-plugin xfce4-battery-plugin xfce4-datetime-plugin xfce4-places-plugin"
packages="$packages xfce4-pulseaudio-plugin pavucontrol network-manager-applet blueman system-config-printer"
packages="$packages xfce4-whiskermenu-plugin xfce4-docklike-plugin gucharmap" #touchegg
packages="$packages xfce4-weather-plugin xfce4-clipman-plugin" #xfce4-notes-plugin, xfce4-calculator-plugin
packages="$packages xfce4-terminal thunar thunar-volman tumbler libgsf-1-114 thunar-archive-plugin"
packages="$packages gvfs gvfs-backends 7zip zip unrar-free file-roller"
packages="$packages xfce4-appfinder geany geany-plugins geeqie celluloid minidlna" #gspell mousepad ristretto parole
#packages="$packages gst-libav gst-plugin-va gst-plugins-base gst-plugins-good gst-plugins-bad gst-plugins-ugly gst-plugin-pipewire"
packages="$packages papers simple-scan qalculate-gtk hunspell" #galculator
packages="$packages mate-polkit gnome-keyring secrets" #authenticator seahorse
packages="$packages fonts-dejavu fonts-liberation fonts-roboto" #libreoffice
packages="$packages syncthing" #(geany requires webkitgtk-4.1) libwebkitgtk-6.0-4 epiphany firefox-esr thunderbird claws-mail litehtml libical
packages="$packages gparted mtools gpart"
packages="$packages compiz-core compiz-plugins-main compiz-gnome"
#packages="$packages build-essential pkgconf cmake libthunarx-3-dev libgtk-3-dev gettext" #to compile linomad packages

#i18n packages:
#for lang in $FF_I18N; do packages="$packages firefox-esr-l10n-$lang"; done
#for lang in $TB_I18N; do packages="$packages thunderbird-l10n-$lang"; done
#for lang in $LO_I18N; do packages="$packages libreoffice-l10n-$lang"; done
#for lang in $HS_I18N; do packages="$packages hunspell-$lang"; done

echo -e "\nInstall Debian…"
DEBIAN_FRONTEND=noninteractive chroot $sysroot apt -y install $packages
chroot $sysroot apt -y autoremove --purge xarchiver xterm gnome-icon-theme libwebkitgtk-6.0-4 #FIX (no deps)


echo -e "\nInstall LiNomad…"
chroot $sysroot dpkg -i packages/fox-echo/live-system_*.deb
chroot $sysroot dpkg -i packages/fox-echo/thunar-encryption-plugin_*.deb
chroot $sysroot dpkg -i packages/fox-echo/gsettings-datetime_*.deb
chroot $sysroot dpkg -i packages/fox-echo/gsettings-accounts_*.deb
chroot $sysroot dpkg -i packages/fox-echo/greadymedia_*.deb


echo -e "\nAdd AppImages integration script…"
wget -O $sysroot/usr/local/bin/appimages.sh https://fox-echo.info/linomad/res/pkg/appimage.sh
chmod +x $sysroot/usr/local/bin/appimages.sh


echo -e "\nRun post-install actions…"
echo "$HOSTNAME" > $sysroot/etc/hostname
echo -e "127.0.0.1\t$HOSTNAME" > $sysroot/etc/hosts
sed 's/Hidden=true/Hidden=false/' -i $sysroot/usr/share/icons/Adwaita/index.theme
#echo -e '#!/bin/sh\nexport GTK_CSD=1' > $sysroot/etc/profile.d/gtk-csd.sh
echo -e '#!/bin/sh\nexport GTK_CSD=1' > $sysroot/etc/skel/.xsessionrc

echo -e "\nConfigure system boot…"
chroot $sysroot systemctl disable minidlna
sed 's/^#\?Storage=.*$/Storage=volatile/' -i $sysroot/etc/systemd/journald.conf #if this is what You want !
echo -e "tmpfs\t/tmp\t\ttmpfs\tdefaults\t0 0" >> $sysroot/etc/fstab


echo -e "\nLocalize system…"
for lang in $LC_I18N; do sed "s/^# \($lang.UTF-8\)/\1/" -i $sysroot/etc/locale.gen; done
chroot $sysroot locale-gen
chroot $sysroot update-locale LANG=fr_FR.UTF-8 LANGUAGE="fr"

if [ ! -z "$LANG" ]; then echo "LANG=$LANG" > $sysroot/etc/locale.conf; fi

if [ ! -z "$KEYMAP" ]; then
	echo XKBLAYOUT="$KEYMAP" > $sysroot/etc/default/keyboard
	cat > $sysroot/etc/X11/xorg.conf.d/00-keyboard.conf << EOF
Section "InputClass"
	Identifier "system-keyboard"
	MatchIsKeyboard "on"
	Option "XkbLayout" "$KEYMAP"
EndSection
EOF
fi

if [ ! -z "$TIMEZONE" ]; then ln -sf /usr/share/zoneinfo/$TIMEZONE $sysroot/etc/localtime; fi


echo -e "\nConfigure users…"
wget -O - https://fox-echo.info/linomad/res/cfg/skel-xfce.tar.gz | tar -xzv -C $sysroot/etc/
chroot $sysroot useradd -m -g users -s /bin/bash -G lpadmin,scanner,plugdev,netdev,cdrom,audio,video,sudo,bluetooth,kvm,disk,dialout $USERNAME
echo -e "root:$PASSWORD\n$USERNAME:$PASSWORD" | chroot $sysroot chpasswd
sed -e 's/rwh$/frwh/' -i $sysroot/etc/login.defs #to allow users changing their name


echo -e "\nSetup Compiz…"
cat > $sysroot/usr/local/bin/compiz-tearfree << EOF
#!/bin/sh
xrandr | grep ' connected' | cut -f1 -d' ' | while read display; do
	xrandr --output \$display --set TearFree on
done
sleep 0.1
exec compiz --replace
EOF
chmod +x $sysroot/usr/local/bin/compiz-tearfree
cat > $sysroot/etc/xdg/autostart/compiz.desktop << EOF
[Desktop Entry]
Version=1.0
Name=Compiz
Comment=Run Compiz window manager
Icon=compiz
Exec=compiz-tearfree
Terminal=false
Type=Application
Hidden=true
EOF


echo -e "\nTweak applications menu…":
#ln -sf /usr/lib/webkit2gtk-4.1/MiniBrowser $sysroot/usr/bin/webkitgtk (debian 13)
ln -sf /usr/lib/x86_64-linux-gnu/webkit2gtk-4.1/MiniBrowser $sysroot/usr/bin/webkitgtk #geany-plugin dep
#ln -sf /usr/lib/x86_64-linux-gnu/webkitgtk-6.0/MiniBrowser $sysroot/usr/bin/webkitgtk
cat > $sysroot/usr/share/applications/webkitgtk.desktop << EOF
[Desktop Entry]
Exec=/usr/bin/webkitgtk https://duckduckgo.com
Icon=org.xfce.webbrowser
Type=Application
Categories=Network;WebBrowser;
Name=WebKitGTK Browser
MimeType=text/html;text/xml;application/xhtml+xml;application/vnd.mozilla.xul+xml;text/mml;x-scheme-handler/http;x-scheme-handler/https;
EOF

for app in xfce4-clipman display-im7.q16; do
	if [ -f $sysroot/usr/share/applications/$app.desktop ]; then
		sed /NoDisplay/d -i $sysroot/usr/share/applications/$app.desktop
		echo "NoDisplay=true" >> $sysroot/usr/share/applications/$app.desktop
	fi
done
sed 's/;Education;Science;Math//' -i $sysroot/usr/share/applications/qalculate-gtk.desktop
chroot $sysroot update-desktop-database /usr/share/applications/


echo -e "\nDisable Firefox disk cache…"
mkdir -p  $sysroot/usr/lib/firefox-esr/defaults/pref/
cat > $sysroot/usr/lib/firefox-esr/defaults/pref/autoconfig.js << EOF
pref("general.config.filename", "firefox.cfg");
pref("general.config.obscure_value", 0);
EOF
echo -e "\ndefaultPref(\"browser.cache.disk.enable\", false);" > $sysroot/usr/lib/firefox-esr/firefox.cfg


if mountpoint -q $sysroot; then #if installation is done on a partition
	echo -e "\nInstall boot loader…"
	syspart=$(mount | grep " on $sysroot type " | cut -f1 -d' ')
	uuid=$(lsblk -n -o UUID $syspart)
	fs=$(lsblk -n -o FSTYPE $syspart) #fs=$(mount | grep " on $sysroot type " | cut -f5 -d' ')
	echo -e "\n#$syspart\nUUID=$uuid / $fs defaults 1 1" >> $sysroot/etc/fstab
	disk="/dev/"$(ls -d /sys/block/*/$(basename $syspart) | cut -f4 -d'/')
	efipart=$(lsblk -o PATH,PARTTYPE -rn $disk | sed -n '/ c12a7328-f81f-11d2-ba4b-00a0c93ec93b$/p' | cut -f1 -d' ') #auto-detected
	if [ ! -z "$efipart" ]; then #GPT / UEFI
		uuid=$(lsblk -n -o UUID $efipart)
		fs=$(lsblk -n -o FSTYPE $efipart) #fs=vfat
		echo -e "\n#$efipart\nUUID=$uuid /boot/efi $fs defaults 1 1" >> $sysroot/etc/fstab
		mkdir -p $sysroot/boot/efi
		mount $efipart $sysroot/boot/efi
		mount --bind /sys/firmware/efi/efivars $sysroot/sys/firmware/efi/efivars
		chroot $sysroot grub-install --target x86_64-efi
		umount $sysroot/sys/firmware/efi/efivars
		umount $sysroot/boot/efi
	fi
	chroot $sysroot grub-mkconfig -o /boot/grub/grub.cfg
	if mount | grep -q " on $sysroot/home type "; then
		homepart=$(mount | grep " on $sysroot/home type " | cut -f1 -d' ')
		uuid=$(lsblk -n -o UUID $homepart)
		fs=$(lsblk -n -o FSTYPE $homepart)
		echo -e "\n#$homepart\nUUID=$uuid /home $fs defaults 1 1" >> $sysroot/etc/fstab
	fi
fi


echo -e "\nCleaning…"
umount $sysroot/packages/; rmdir $sysroot/packages/
umount -R $sysroot/dev
umount -R $sysroot/sys
umount $sysroot/proc
