#!/bin/bash

# Prepared for antiX under the GPLv2 license
# Copyright (C) 2026 ProwlerGr <Prowler73@gmail.com>

# Localisation
TEXTDOMAINDIR=/usr/share/locale
TEXTDOMAIN=antix-init-diversity-manager

##[ "$UID" -eq 0 ] || exec sudo bash "$0" "$@"

trap cleanup EXIT 

INIT_LIST="$(mktemp -p /dev/shm)"

cleanup() {
    ### Remove temporary files
    rm -f -- "$INIT_LIST"
    echo "Cleanup and exiting"
}

# Generate available inits list
echo $(readlink /sbin/init) > "$INIT_LIST"
[ -x /lib/sysvinit/init ] && echo "/lib/sysvinit/init" >> "$INIT_LIST"
[ -x /lib/systemd/systemd ] && echo "/lib/systemd/systemd" >> "$INIT_LIST"
[ -x /sbin/upstart ] && echo "/sbin/upstart" >> "$INIT_LIST"
[ -x /lib/s6-rc/s6-rc-init ] && echo "/lib/s6-rc/s6-rc-init" >> "$INIT_LIST"
[ -x /lib/s6-66/s6-66-init ] && echo "/lib/s6-66/s6-66-init" >> "$INIT_LIST"
[ -x /lib/openrc/openrc-init ] && echo "/lib/openrc/openrc-init" >> "$INIT_LIST"
[ -x /lib/dinit/dinit ] && echo "/lib/dinit/dinit" >> "$INIT_LIST"
[ -x /lib/runit/runit-init ] && echo "/lib/runit/runit-init" >> "$INIT_LIST"
[ -x /lib/shepherd/shepherd ] && echo "/lib/shepherd/shepherd" >> "$INIT_LIST"
[ -x /lib/sinit/sinit ] && echo "/lib/sinit/sinit" >> "$INIT_LIST"


# Prepare yadlist & remove dubicated entry
yadlist=( $(awk '!seen[$0]++' "$INIT_LIST") )

# Launch YAD
result=$(yad --list --fixed --width=500 --height=320 \
    --title=$"antiX Init Diversity Manager" \
    --column=Installed-Inits \
    --text=$"Change GRUB Settings to either:
 - Show All Inits: 		  Expand all available init systems under the Main GRUB Screen
 - Show Only Main Init:   Hide secondary init systems under the 'Advanced' GRUB sub-menu  
				
<b>Double-Click to change Main Init</b> (linked to <i>/sbin/init</i> )" \
    --button="gtk-cancel:40" \
	--button=$"Show Only Main Init:20" \
	--button=$"Show All Inits:10" \
	--dclick-action="ln -sf %s /sbin/init" \
    "${yadlist[@]}") 

# Capture the button pressed via exit code
ret=$?

# Process based on which button was clicked
case $ret in
	40) echo $"Cancelled" 
		;;
    20) mkdir -p /etc/init-diversity && echo "" > /etc/init-diversity/grub_hide_cmdline_inits && [ ! -e /live/aufs ] && update-grub;
		yad --width=100 --height=75 --fixed \
		--title=$"antiX Init Diversity Manager" \
		--button Exit \
		--info --text=$"Only the main init system will be shown on the Main GRUB Screen"
		;;
    10) rm -rf /etc/init-diversity/grub_hide_cmdline_inits && [ ! -e /live/aufs ] && update-grub;
		yad --width=100 --height=75 --fixed \
		--title=$"antiX Init Diversity Manager" \
		--button Exit \
		--info --text=$"All init systems will be shown on the Main GRUB Screen" 
		;;
    *) echo $"Window closed or ESC pressed." 
		;;
esac
