#!/bin/bash
# shellcheck disable=SC2015
# shellcheck disable=SC1091
set -e

def_pacman_config(){
    local TEMP_CONF
    TEMP_CONF=$(mktemp)
    # Configuring Backup Repo
    echo -e "[snigdhaos-core]\nServer = https://snigdhalinux.github.io/snigdhaos-core/x86_64" >"$TEMP_CONF"
    echo "$TEMP_CONF"
}

# Credit            : Garuda Linux
# URL               : https://garudalinux.org/
# Script Source     : https://gitlab.com/garuda-linux/pkgbuilds/-/blob/main/garuda-update/garuda-update

self_update(){
    local EXTRA_PARAMS=()
    if [ "$DATABASE_UPDATED" == "force" ]; then
        $PACMAN -Syy && DATABASE_UPDATED=true || true
    elif [ "$DATABASE_UPDATED" != "true" ]; then
        $PACMAN -Syy && DATABASE_UPDATED=true || true
    fi
    [ "$DATABASE_UPDATED" != "true" ] && local MIN_PACMAN_CONF && MIN_PACMAN_CONF="$(def_pacman_config)" && $PACMAN --config "$MIN_PACMAN_CONF" -Syy && EXTRA_PARAMS=("--config" "$MIN_PACMAN_CONF") || true
    $INT
    if $PACMAN "${EXTRA_PARAMS[@]}" -Qu snigdhaos-updater &>/dev/null; then
        local success=true
        if ! SNAP_PAC_SKIP=y SKIP_AUTOSNAP='' $PACMAN "${EXTRA_PARAMS[@]}" -Sdd snigdhaos-updater --needed --noconfirm; then
            $INT
            unshare -m bash -c 'mount -t tmpfs tmpfs /usr/share/libalpm/hooks && { [ ! -d /var/cache/pacman/pkg ] mount -t tmpfs tmpfs /var/cache/pacman/pkg; } && eval "$@"' -- SNAP_PAC_SKIP=y SKIP_AUTOSNAP='' "$PACMAN" "${EXTRA_PARAMS[@]}" --hookdir "/usr/share/libalpm/hooks" -Sdd snigdhaos-updater --needed --noconfirm || success=false
        fi
        $INT
        if [ "$success" == "true" ]; then
            SNIGDHAOS_UPDATER_SELFUPDATE=2 exec /usr/bin/snigdhaos-updater "$@"
        fi
    fi
    $INT
}

INT=true
trap "INT=false" INT

if [[ $EUID -ne 0 ]]; then
    exec sudo --preserve-env="SKIP_MIRRORLIST"
    exit 1
fi

if [ "$1" == "remote" ]; then
	exec bash -c "VERSION=6 . <(wget -qO- https://raw.githubusercontent.com/Snigdha-OS/snigdhaos-pkgbuilds/master/common/snigdhaos-updater/remote) \"\$@\"" remote "${@:2}"
fi

if [ -n "$PACMAN_EXE" ]; then
    PACMAN="$PACMAN_EXE"
else
    PACMAN="pacman"
fi

export PACMAN

DATABASE_UPDATED=false
if [ -n "$SNIGDHAOS_UPDATER_SELFUPDATE" ]; then
    DATABASE_UPDATED=true
fi
self_update "$@"

source /usr/lib/snigdhaos/snigdhaos-updater/core-script