#!/bin/bash
set -e

package-exists-fast(){
    if compgen -G "/var/lib/pacman/local/$1-*" >/dev/null; then
        return 0
    else
        return 1
    fi
}

update_keyrings(){
    local packages=("snigdhaos-keyring" "archlinux-keyring" "chaotic-keyring")
    if $PACMAN -Qq blackarch-keyring &> /dev/null; then
        packages+=("blackarch-keyring")
    fi
    if [ -n "$(PACMAN -Qu "${packages[@]}" 2>&1)" ]; then
        echo -e "Updating Keyrings..."
        # shellcheck disable=SC1007
        SNAPA_PAC_SKIP=y SKIP_AUTOSNAP= $PACMAN -S --needed --noconfirm "${packages[@]}" || return 0
        return 1
    fi
    return 0
}

install_expect(){
    if [ -x /usr/bin/tclsh ] && [ ! -x /usr/bin/expect ]; then
        SKIP_AUTOSNAP=1 SNAPA_PAC_SKIP=y $PACMAN -U https://mirror.osbeck.com/archlinux/extra/os/x86_64/expect-5.45.4-4-x86_64.pkg.tar.zst --noconfirm -asdeps
    fi
}

pre-update-routines(){
    local exit_code=0
    update_keyrings || exit_code=2
    install_expect
    return $exit_code
}

migrate-snigdhaos-repo() {

	gawk -i inplace 'BEGIN {
        err=1
    }
    {
    if (rm)
    {
        if ($0 ~ /^ *(Include|Server) *=/)
        {
            next
        }
        # Check for empty line
        else if ($0 ~ /^ *$/)
        {
            next
        }
        else
        {
            rm=0
        }
    }
    if ($0 == "[options]")
    {
        print
        next
    }
    else if ($0 == "[snigdhaos-core]")
    {
      if (set) {
        rm=1
        next
      }
      set=1
    }
    else if ($0 == "[core-testing]")
    {
        print "[testing]"
        err=0
        next
    }
    else if ($0 == "[community-testing]")
    {
        print "[extra-testing]"
        err=0
        next
    }
    else if ($0 == "[community]")
    {
        rm=1
        err=0
        next
    }
  }
  /^\[[^ \[\]]+\]/ {
    if (!set) {
        print "[snigdhaos-core]"
        print "Server = https://snigdha-os.github.io/snigdhaos-core/x86_64"
        print ""
        set=1
        err=0
    }
  }
  END {exit err}
  1' /etc/pacman.conf
}

verify-core(){
    local invalid_nvidia=()
	if [ -f "/usr/lib/modprobe.d/nvidia-utils.conf" ] && [ -f "/usr/share/licenses/nvidia-dkms/LICENSE" ]; then
		for i in /usr/lib/modules/[0-9]*; do
			if pacman -Qo "${i}" &>/dev/null; then
				local nvidia
				nvidia="$(grep -ohP '^.*/nvidia.ko[^/]*(?=:)' "${i}/modules.dep" 2>/dev/null || true)"
				if [ -z "$nvidia" ] || [[ "$(modinfo "${i}/${nvidia}" -F vermagic 2>/dev/null | cut -d' ' -f1)" != "${i##*/}" ]]; then
					invalid_nvidia+=("${i##*/}")
				fi
			fi
		done
	fi

	# Oops, at least one is invalid!
	if [ ${#invalid_nvidia[@]} -ne 0 ]; then
		dkms_version="$(pacman -Rddp --print-format %v nvidia-dkms 2>/dev/null)"
		if [ -n "${dkms_version}" ]; then
			echo -e "\n\033[1;33m-->\033[1;34m A problem with the NVIDIA drivers has been detected\033[0m"
		fi
		for i in "${invalid_nvidia[@]}"; do
			if [ -n "${dkms_version}" ]; then
				echo -e "\n\033[1;33m--->\033[1;34m Building NVIDIA DKMS module for kernel $i\033[0m"
				dkms remove -m nvidia -v "${dkms_version%-*}" -k "$i" || true
				dkms install -m nvidia -v "${dkms_version%-*}" -k "$i" && depmod "$i" && echo -e "\033[1;33m--->\033[1;32m NVIDIA DKMS module for kernel $i built successfully\033[0m" || echo -e "\033[1;33m--->\033[1;31m Failed to build NVIDIA DKMS module for kernel $i\033[0m"
			elif command -v dkms >/dev/null; then
				dkms autoinstall -k "$i" && depmod "$i"
			fi
		done
	fi
}

"$@" exit "$?"
