#!/bin/sh
set -ex

gnomepkgs="gnome-tweaks geary lollypop menulibre pamac-aur
           $(paru -Sqg gnome | sed -E '/gdm|software/d')"

comment(){
    local file="$1";shift
    sudo perl -i -pe "s/^#* */# / if /$@/" $file
}

uncomment(){
    local file="$1";shift
    sudo perl -i -pe "s/^#* *// if /$@/" $file
}

gui_off (){
    dotdrop install -f

    # comment   /etc/mkinitcpio.conf "HOOKS.* plymouth"
    # comment   /etc/default/grub "GRUB_CMDLINE_LINUX_DEFAULT.* splash"

    paru -D --asdeps $gnomepkgs
    paru -Qqdt | paru -Rcs --noconfirm - || true
    # sudo mkinitcpio -P

    sudo systemctl --now enable  iwd dhcpcd greetd
    sudo systemctl --now disable gdm gdm-plymouth NetworkManager
}

gui_on (){

    paru -Syu --noconfirm --needed gnome-defaults-list $gnomepkgs || true
    cp /usr/share/applications/gnome-mimeapps.list ~/.config/mimeapps.list

    # uncomment   /etc/mkinitcpio.conf "HOOKS.* plymouth"
    # uncomment   /etc/default/grub "GRUB_CMDLINE_LINUX_DEFAULT.* splash"

    # paru -S plymouth plymouth-theme-arch-glow gdm-plymouth --noconfirm --needed
    # sudo plymouth-set-default-theme arch-glow
    # sudo plymouth-set-default-theme -R arch-glow

    sudo systemctl --now disable iwd dhcpcd greetd
    sudo systemctl --now enable NetworkManager gdm gdm-plymouth
}

restart_gdm(){
    if systemctl -q is-active gdm-plymouth
    then
        sudo systemctl restart gdm-plymouth
    fi

    if systemctl -q is-active gdm
    then
        sudo systemctl restart gdm
    fi
}

x11_on(){
    uncomment   /etc/gdm/custom.conf "Wayland"
    perl -i -pe 's/false/true/ if /layers.acceleration.force-enable/' ~/.mozilla/firefox/*default-release*/prefs*js
    restart_gdm
}

x11_off(){
    comment     /etc/gdm/custom.conf "Wayland"
    perl -i -pe 's/true/false/ if /layers.acceleration.force-enable/' ~/.mozilla/firefox/*default-release*/prefs*js
    restart_gdm
}

if [ "$1" = "on" ];then
    gui_on
elif [ "$1" = "off" ];then
    gui_off
elif [ "$1" = "x11" ];then
    if [ "$2" = "on" ];then
        x11_on
    elif [ "$2" = "off" ];then
        x11_off
    fi
else
    echo "Usage: "
    echo "  $0      <on|off>"
    echo "  $0 x11  <on|off>"
fi
