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

# Arch 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.02.15


echo -e "\nCheck prerequisites…"
if [ $(id -u) != 0 ]; then
    echo "error: $(basename $0) must be run as root"
    exit 1
fi

missing=""
for command in wget; do
    if [ -z "$(which $command 2>/dev/null)" ]; then
        echo "error: missing command $command"
        missing="$command $missing"
    fi
done
if (( $# == 0 )) && [ -z "$(which pacstrap 2>/dev/null)" ]; then
    echo "error: missing command pacstrap"
    missing="arch-install-scripts $missing"
fi
if [ -z "$(which pacman 2>/dev/null)" ]; then
    echo "error: missing command pacman"
    missing="pacman-package-manager $missing"
fi
if [ ! -z "$missing" ]; then
    echo "packages to install: $missing"
    exit 2
fi


echo -e "\nConfigure options:"
hostname=${HOSTNAME:-linomad}
username=${USERNAME:-linomad}
password=${PASSWORD:-linomad}

#LC (locale), FF (firefox), TB (thunderbird), LO (libreoffice), HS (hunspell) and TA (tesseract)
lci18n=${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)
#~ ffi18n=${FF_I18N:-"fr de es-es it pt-pt"}   #FireFox (ar bn hi-in ja ru zh-cn)
#~ tbi18n=${TB_I18N:-"fr de es-es it pt-pt"}   #ThunderBird (ar ja ru zh-cn)
#~ loi18n=${LO_I18N:-"fr de es it pt"} #LibreOffice (ar bn hi ja ru zh-cn)
hsi18n=${HS_I18N:-"fr de en_us es_any it"}   #HunSpell (ru) - required by LibreOffice / Thunderbird
#~ tai18n=${TA_I18N:-"fra deu eng spa ita por"} #TesserAct ( ara ben hin jpn rus chi_sim)
echo -e "\thostname=$hostname\n\tusername=$username\n\tpassword=$password\n\tlanguages=$lci18n"


echo -e "\nSetup source and destination:"
sysroot=${1:-"system"}; sysroot=${sysroot%/} #remove trailing slash
chroot=""
pacstrap="pacman -Syu"
pacman="pacman --noconfirm"
if [ ! -z "$sysroot" ]; then
    chroot="chroot $sysroot"
    pacstrap="pacstrap $sysroot"
    pacman="pacman --noconfirm --root $sysroot"
fi
linomad=${4:-"packages"}; linomad=${linomad%/}
mirror=${MIRROR:-'https://geo.mirror.pkgbuild.com/$repo/os/$arch'}
echo -e "\tmirror=$mirror\n\tdestination=$sysroot/"


echo -e "\nSync packages…"
if [ ! -d $linomad/ ]; then
	wget -r -np -nH --cut-dirs=3 --reject "index.html*" -P $linomad/ https://fox-echo.info/linomad/res/pkg/archlinux/
	mv $linomad/archlinux/* $linomad/; rmdir $linomad/archlinux
fi


#base packages:
packages=""
packages="$packages base linux linux-firmware amd-ucode intel-ucode mkinitcpio grub efibootmgr os-prober"
packages="$packages iptables-nft dosfstools exfatprogs fscrypt cryfs f2fs-tools encfs"
packages="$packages man-db less sudo which vis lua-lpeg curl wget rsync tree unzip nano inotify-tools"
packages="$packages squashfs-tools xorriso arch-install-scripts" #live-system / linomad

#driver packages:
packages="$packages power-profiles-daemon" #tlp
packages="$packages wireplumber pipewire-pulse pipewire-alsa pipewire-jack"
packages="$packages iwd broadcom-wl networkmanager networkmanager-openvpn wireguard-tools"
packages="$packages mesa" #hardware video acceleration (mesa-utils, libva-utils)
packages="$packages libva-intel-driver intel-media-driver" #Intel hardware video acceleration (libvpl vpl-gpu-rt)
packages="$packages libvdpau-va-gl libva-nvidia-driver" #hardware video acceleration translations layers (vdpauinfo)
#packages="$packages vulkan-nouveau vulkan-radeon vulkan-intel" #Vulkan drivers (vulkan-tools)
packages="$packages cups cups-pdf sane-airscan nss-mdns" #driverless printing and scanning

#desktop packages:
packages="$packages xorg-server xorg-drivers xorg-xhost xdg-utils xdg-user-dirs xdg-desktop-portal-gtk"
packages="$packages lightdm-gtk-greeter lightdm-gtk-greeter-settings light-locker dconf-editor"
#packages="$packages qt6ct"
packages="$packages xfce4-session xfwm4 xfwm4-themes xfce4-panel xfdesktop xfce4-notifyd"
packages="$packages xfce4-power-manager xfce4-settings xfce4-screensaver xfce4-screenshooter xfce4-taskmanager labwc"
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 thunar-archive-plugin"
packages="$packages gvfs gvfs-gphoto2 gvfs-mtp gvfs-smb samba 7zip zip unrar file-roller gvfs-afc gvfs-goa gvfs-google gvfs-onedrive gvfs-wsdd gvfs-dnssd"
packages="$packages xfce4-appfinder geany geany-plugins geeqie celluloid minidlna" #gspell mousepad ristretto parole
packages="$packages gst-libav gstreamer-vaapi gst-plugins-base gst-plugins-good gst-plugins-bad gst-plugins-ugly gst-plugin-pipewire"
packages="$packages papers simple-scan qalculate-gtk polkit-gnome gnome-keyring seahorse secrets" #authenticator galculator
packages="$packages ttf-dejavu ttf-liberation ttf-carlito ttf-roboto ttf-roboto-mono" #libreoffice-fresh
packages="$packages syncthing" #(geany requires webkitgtk-4.1) webkitgtk-6.0 epiphany firefox thunderbird claws-mail litehtml libical
packages="$packages gparted mtools gpart"
packages="$packages fuse2 libxml2-legacy" #sdl12-compat (legacy AppImage support)

#i18n packages:
#~ for lang in $ffi18n; do packages="$packages firefox-i18n-$lang"; done
#~ for lang in $tbi18n; do packages="$packages thunderbird-i18n-$lang"; done
#~ for lang in $loi18n; do packages="$packages libreoffice-fresh-$lang"; done
for lang in $hsi18n; do packages="$packages hunspell-$lang"; done


echo -e "\nInstall ArchLinux…"
if [ ! -z "$sysroot" ]; then mkdir $sysroot; fi
$pacstrap $packages
if [ ! -z "$sysroot" ]; then
    for d in sys proc dev; do mount --bind /$d $sysroot/$d; done
fi


echo -e "\nInstall LiNomad…"
$pacman -U $linomad/fox-echo/live-system-*.pkg.tar.zst
$pacman -U $linomad/fox-echo/thunar-encryption-plugin-*.pkg.tar.zst
$pacman -U $linomad/fox-echo/gsettings-datetime-*.pkg.tar.zst
$pacman -U $linomad/fox-echo/gsettings-accounts-*.pkg.tar.zst
$pacman -U $linomad/fox-echo/greadymedia-*.pkg.tar.zst


echo -e "\nsetup pacman…"
echo "nameserver 9.9.9.9" >> $sysroot/etc/resolv.conf
$chroot pacman-key --init
$chroot pacman-key --populate
sed '/^Server = /d' -i $sysroot/etc/pacman.d/mirrorlist
echo -e "\nServer = $mirror" >> $sysroot/etc/pacman.d/mirrorlist
$chroot pacman -Sy


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
ln -sf vis $sysroot/usr/bin/vi
echo -e '#!/bin/sh\nexport GTK_CSD=1' > $sysroot/etc/profile.d/gtk-csd.sh


echo -e "\nConfigure system boot…"
$chroot systemctl enable lightdm
$chroot systemctl enable NetworkManager
$chroot systemctl enable bluetooth
$chroot systemctl enable cups
#sed -e 's/^#NTP=.*$/NTP=0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org/' -e 's/#FallbackNTP=/FallbackNTP=/' -i $sysroot/etc/systemd/timesyncd.conf
$chroot systemctl enable systemd-timesyncd
sed 's/resolve/mdns_minimal \[NOTFOUND=return\] resolve/' -i $sysroot/etc/nsswitch.conf #driverless printing & scanning
$chroot systemctl enable avahi-daemon
sed 's/#Storage=auto/Storage=volatile/' -i $sysroot/etc/systemd/journald.conf
echo -e "tmpfs\t/tmp\t\ttmpfs\tdefaults\t0 0" >> $sysroot/etc/fstab


echo -e "\nLocalize system…"
for lang in $lci18n; do sed "s/^#\($lang.UTF-8\)/\1/" -i $sysroot/etc/locale.gen; done
$chroot locale-gen
if [ ! -z "$LANG" ]; then echo "LANG=$LANG" > $sysroot/etc/locale.conf; fi

vcmap=$(localectl status | grep "VC Keymap" | cut -c16- | cut -f1 -d' ')
if [ ! -z "$vcmap" ]; then echo "KEYMAP=$vcmap" > $sysroot/etc/vconsole.conf; fi

x11map=$(localectl status | grep "X11 Layout" | cut -c16- | cut -f1 -d' ')
if [ ! -z "$x11map" ]; then
	sed '/^XKBLAYOUT=/d' -i $sysroot/etc/vconsole.conf
	echo -e "XKBLAYOUT=$x11map" >> $sysroot/etc/vconsole.conf
    cat > $sysroot/etc/X11/xorg.conf.d/00-keyboard.conf << EOF
Section "InputClass"
    Identifier "system-keyboard"
    MatchIsKeyboard "on"
    Option "XkbLayout" "$x11map"
EndSection
EOF
fi

if [ -h /etc/localtime ]; then ln -sf $(readlink /etc/localtime) $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 useradd -m -g users -G wheel,disk,input $username
echo -e "root:$password\n$username:$password" | $chroot chpasswd
sed 's/# \(%wheel ALL=(ALL:ALL) ALL\)/\1/' -i $sysroot/etc/sudoers
sed -e 's/rwh$/frwh/' -i $sysroot/etc/login.defs #to allow users changing their name


echo -e "\nTweak applications menu…":
cat > $sysroot/usr/share/applications/syncthing-ui.desktop << EOF
[Desktop Entry]
Name=Syncthing Web UI
GenericName=File synchronization UI
Comment=Opens Syncthing's Web UI in the default browser (Syncthing must already be started).
Exec=syncthing browser
Icon=emblem-synchronizing
Terminal=false
Type=Application
Keywords=synchronization;interface;
Categories=Network;FileTransfer;P2P
EOF

ln -sf /usr/lib/webkit2gtk-4.1/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 cups mpv qv4l2 qvidcap; 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 update-desktop-database /usr/share/applications/


echo -e "\nDisable Firefox disk cache…"
mkdir -p $sysroot/usr/lib/firefox/defaults/pref
cat > $sysroot/usr/lib/firefox/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/firefox.cfg #better for live-system on USB media



if mount | grep -q " on $sysroot type "; 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\n$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\n$uuid /boot/efi $fs defaults 1 1" >> $sysroot/etc/fstab
        mount $efipart $sysroot/boot/efi; mount --bind /sys/firmware/efi/efivars $sysroot/sys/firmware/efi/efivars
        $chroot grub-install --target x86_64-efi
        umount $sysroot/sys/firmware/efi/efivars; umount $sysroot/boot/efi
    else #MBR / BIOS (legacy) - probably in a virtual machine
        $chroot grub-install --target i386-pc $disk
    fi
    $chroot 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\n$uuid /home $fs defaults 1 1" >> $sysroot/etc/fstab
    fi
fi


echo -e "\Cleaning…"
gpgps=$(ps -u root | grep gpg-agent | awk '{ print $1 }')
if [ ! -z "$gpgps" ]; then kill $gpgps; sleep 5; fi
rm $sysroot/var/cache/pacman/pkg/* #pacman -Scc
for d in sys proc dev; do umount $sysroot/$d; done
