# Copyright Argent Linux Authors 2015-2025
# License: GPLv2

#!/usr/bin/env bash

source /etc/portage/make.conf

# generic Argent variables
export ADD_OPTS="${ADD_OPTS:-}"

# export function for other gentoo distributions to use
export EPKG_DISTRO_SET="argent"

export ENABLE_COLOR="\e[1;49;34m"
export DISABLE_COLOR="\e[0m"

export PORTAGE_DIR="${PORTDIR}"
export ARGENT_OVERLAY="/var/db/repos/argent-ws"

# import gentoo functions, this has not been ported to lib64 yet
source /lib/gentoo/functions.sh

# generic gentoo variables
export PORTAGE_GROUP="${PORTAGE_GROUP:-portage}"

checkroot() {
	if [[ "$(whoami)" != root ]] ; then
		eerror "You're not root?...No cookies for you, go away !!!"
		exit 1
	fi
}

checksystemmode() {
	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-srcmode" ]] ; then
		eerror "The system is set to SRCMODE (full Gentoo mode), cowardly refusing to run!"
		exit 1
	fi
}

checkportageconfig() {
	# running update on argent specific gentoo settings

	pushd /opt/argentws-build > /dev/null 2>&1 || return
	git remote update > /dev/null 2>&1

	CONFHASH=$(git rev-parse @)
	RCONFHASH=$(git rev-parse @{u})
	
	if [[ ! -e .git ]] ; then
		echo -e ""
		eerror "You do not have any connection with the Argent main server"
		eerror "Establish a .git connection to the main Argent EPKG server"
		# shellcheck disable=SC2027
		eerror "Or use ""$ENABLE_COLOR""avasile""$DISABLE_COLOR"" to switch stance"
		eerror "Ignoring local changes."
		echo -e ""
	elif [ "${CONFHASH}" != "${RCONFHASH}" ] ; then
		eerror "portage config is out of date, run "epkg update" first"
	fi
	popd > /dev/null 2>&1
}

checkportagetree() {
	# running update on gentoo snapshotted overlay

	pushd "${PORTAGE_DIR}" > /dev/null 2>&1 || return
	git remote update > /dev/null 2>&1

	export TREEHASH=$(git rev-parse @)
	export RTREEHASH=$(git rev-parse @{u})

	if [ "${TREEHASH}" != "${RTREEHASH}" ] ; then
		eerror "Argent portage tree is out of date, run "epkg update" first"
	fi
	popd > /dev/null 2>&1 || return
}

checkargentoverlay() {
	# running update on argent gentoo overlay

	pushd "${ARGENT_OVERLAY}" > /dev/null 2>&1 || return
	git remote update > /dev/null 2>&1
	export OVERLAYHASH=$(git rev-parse @)
	export ROVERLAYHASH=$(git rev-parse @{u})
	if [  "${OVERLAYHASH}" != "${ROVERLAYHASH}" ] ; then
		eerror "Overlay argent-ws is out of date, run "epkg update" first"
	fi

	popd > /dev/null 2>&1 || return
}

checkmakeconf() {
	# function checking the existence and validity of make.conf
	# in accordance wih gentoo and argentws-build standard

        if [ -e "/etc/portage/make.conf" ] ; then
                . /etc/portage/make.conf
		unset PKGDIR
		export PKGDIR="${PKGDIR:-$(cat /etc/portage/make.conf | grep 'PKGDIR=' | cut -d '"' -f2)}"
	else
                eerror "The file does not match the pattern of environment script"
                echo "Please consider using avasile to change to one of the modes"
                echo "avasile --help"
        fi
}

checkportdir() {
	# function to check the existence of portage and argent/portage.git independent dirs:
	# distfiles and packages
	# the unconventional way here: we import /etc/portage/make.conf into current local function
	checkmakeconf

        # check if ${PORTDIR} exists

        if [ ! -d "${PORTDIR}" ] ; then
                eerror "No such directory: ${PORTDIR}"
                echo "Consider running: epkg update"
                exit 1
        fi

        # check if distfiles exist. Again, we might never know what Gentoo users are up to

        if [ ! -d "${DISTDIR}" ] ; then
                eerror "No such directory: ${DISTDIR}"
                echo "Consider creating the directory with the right ownership:"
                echo "i.e.: chgrp portage ${DISTDIR}"
                exit 1
        fi

        # check if ${PKGDIR} exists

        if [ ! -d "${PKGDIR}" ] ; then
                eerror "No such directory: ${PKGDIR}/"
                echo "Consider creating the directory with the right ownership:"
                echo "i.e.: chgrp portage ${PKGDIR}/"
                exit 1
        fi
}

checksync() {
    if [[ "${EPKG_DISTRO_SET}" == "argent" ]]; then
        if [ -d "/opt/argentws-build/.git" ]; then
            checkportagetree
        else
		ewarn "No portage tree found, you should fetch minimal portage tree via epkg update"
	fi
        if [ -d "$ARGENT_OVERLAY/.git" ]; then
            checkargentoverlay
        else
		ewarn "No argent overlay found, you must eselect enable argent-ws or git clone it in:"
		ewarn "either /var/lib/layman/ or /var/db/repos/"
		ewarn "You also have the alternative to use the distro-reset command avasile --help"
	fi
        checkportageconfig
    fi
}

syncrepos() {
	if [[ -e "/etc/portage/repos.conf/layman.conf" ]] && [[ "$(cat /etc/portage/repos.conf/layman.conf | grep argent-ws )" ]] ; then
		sed -i 's|auto-sync = No|auto-sync = yes|g' /etc/portage/repos.conf/layman.conf
	fi

	emerge --sync
}

set_var_cache_dir() {
	export COLOR_ON="\e[1;49;34m"
	export COLOR_OFF="\e[0m"

	if [ -e "/etc/portage/make.conf" ] ; then
		. /etc/portage/make.conf
		unset PKGDIR
		export PKGDIR="${PKGDIR:-$(cat /etc/portage/make.conf | grep 'PKGDIR=' | cut -d '"' -f2)}"
		unset DISTDIR
		export DISTDIR="${DISTDIR:-$(cat /etc/portage/make.conf | grep 'DISTDIR=' | cut -d '"' -f2)}"
		unset PORTAGE_GROUP
		export PORTAGE_GROUP="${PORTAGE_GROUP:-$(cat /etc/portage/make.conf | grep 'PORTAGE_GROUP=' | cut -d '"' -f2)}"
        else
		eerror "The file does not match the pattern of environment script"
		echo "Please consider using avasile to change to one of the modes"
		echo "avasile --help"
	fi

	echo " "

	if [ ! -e "${PKGDIR}"  ] ; then
		mkdir -p "${PKGDIR}"
		if [ $( stat -c "%G" "${PKGDIR}" ) != "${PORTAGE_GROUP}" ] ; then
			eerror "Please make sure you set $PKGDIR ownership to $PORTAGE_GROUP"
			echo " "
			eerror "Run command: "$COLOR_ON"chgrp $PORTAGE_GROUP {${PKGDIR},${DISTDIR}} "$COLOR_OFF""
			echo " "
			eerror "You can safely cancel now, and run the blue command from above"
			echo " "
		fi
	fi

	if [ ! -e "${DISTDIR}"  ] ; then
		mkdir -p "${DISTDIR}"
		if [ $( stat -c "%G" "${DISTDIR}" ) != "${PORTAGE_GROUP}" ] ; then
			eerror "Please make sure you set $DISTDIR ownership to $PORTAGE_GROUP"
			echo " "
			eerror "Run command: "$COLOR_ON"chgrp $PORTAGE_GROUP {${PKGDIR},${DISTDIR}} "$COLOR_OFF""
			echo " "
		fi
	fi
}

forcesync() {
	# Full update, everything caught in history
	pushd "${PORTAGE_DIR}" > /dev/null 2>&1 || return
	git pull --unshallow
	popd || return

	pushd "${ARGENT_OVERLAY}" > /dev/null 2>&1 || return
	git pull --unshallow
	popd || return

	pushd /opt/argentws-build > /dev/null 2>&1 || return
	git pull --unshallow
	popd || return
}

fetchminimalsync() {
        # fetch minimal portage tree
        # in usermode we don't want the whole tree of gentoo ebuilds
        # but we need portage profiles portage metadata && portage eclasses
        # so make a sparse-checkout, to fetch only what we need
        if [[ ! -d "${PORTAGE_DIR}"/.git ]] ; then
                einfo "Injecting usermode (minimal) gentoo portage tree"
                cd "${PORTAGE_DIR}" && git init > /dev/null 2>&1
                git remote add origin https://gitlab.com/argent/portage.git
                git config core.sparsecheckout true
                echo "profiles/*" >> .git/info/sparse-checkout
                echo "metadata/*" >> .git/info/sparse-checkout
                echo "eclass/*" >> .git/info/sparse-checkout
                echo ".gitignore" >> .git/info/sparse-checkout
                git pull --depth=1 origin master
                git branch -u origin/master master
                rm -rf ""${PORTAGE_DIR}"/profiles/updates"
        else
        # We need minimal git pull if the folder really exists
        pushd "${PORTAGE_DIR}" > /dev/null 2>&1 || return
            git pull --update-shallow
            git pull --depth=1
            git gc --prune=now
        popd || return
    fi

    if [[ ! -d ""${ARGENT_OVERLAY}"/.git" ]] ; then
        einfo "Injecting usermode argent-ws overlay"
        cd "${ARGENT_OVERLAY}" && git init > /dev/null 2>&1
        git remote add origin https://gitlab.com/argent/argent-ws.git
        git config core.sparsecheckout true
                echo "profiles/*" >> .git/info/sparse-checkout
                echo "metadata/*" >> .git/info/sparse-checkout
                echo "eclass/*" >> .git/info/sparse-checkout
                echo ".gitignore" >> .git/info/sparse-checkout
                git pull --depth=1 origin master
                git branch -u origin/master master
                git submodule update --init --recursive --depth=1
                rm -rf ""${PORTAGE_DIR}"/profiles/updates"
    else
        pushd "${ARGENT_OVERLAY}" > /dev/null 2>&1 || return
            git pull --update-shallow
            git pull --depth=1
            git submodule update --init --recursive --depth=1
            git submodule foreach --recursive git prune
            git gc --prune=now
        popd || return
    fi

    pushd /opt/argentws-build/ > /dev/null 2>&1 || return
        git pull --update-shallow
        git pull --depth=1
        git gc --prune=now
    popd || return

}

backuppkg() {
	# function to provide backup packages with own configurations

	# a forenote: although if you run usermode or devmode, the installing packages will already be saved
	# but if you run epkg cleanlocalpkg, you can start all over and save what packages you already configured
	# like saving apache with own configs for example, for future use

	# the unconventional way here: we import /etc/portage/make.conf into current local function
	checkmakeconf

	if [[ $# -eq 0 ]] ; then
		eerror "You have not specified any package to backup"
		echo " "
		exit 1
	fi

	# checking if ${PKGDIR} exists
	# usually it's /usr/portage/ if you're on avasile --usermode or --devmode
	if [ -d "${PKGDIR}" ] ; then
		quickpkg --include-config y --include-unmodified-config y "$@"
		echo ""
		echo "All packages were saved in ${PKGDIR} by category"
		echo "Please make sure these files will not be overwritten!"
		echo "If you consider further backup on the same package"
		echo "consider copying packages from ${PKGDIR} into customized directories"
		echo "Although, not recommended, you can epkg install them by path (from customized directories)"
		echo "To customize directory, you can use variable PKGDIR as: PKGDIR='/location/' epkg backuppkg"
		echo " "
	else
		echo "  "
		eerror "No such directory: ${PKGDIR}"
		echo "Please consider creating the $PKGDIR directory"
		echo "And set $PKGDIR GID to portage!"
		echo " "
		exit 1
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

backupallpkg() {
	# function to *backup all packages in the system* for future use

	# the unconventional way here: we import /etc/portage/make.conf into current local function
	if [[ -z "$@" ]] ; then
		eerror "You have not specified any package to backup"
		echo " "
    	exit 1
    fi

	checkportdir

	eerror "Warning: If you backup everything, make sure you keep the packages safe :)"
	eerror "We cannot take responsibility of safe-guarding the newly backed-up system"

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		eerror "If you continue, you continue at your own risk!"
		eerror "Make sure you keep the backup safe!"
		sleep 3
		if [[ ! -e "/tmp/temporary_list_backup" ]] ; then
			# shellcheck disable=SC2283
			for i in $( qlist -IvC ) ; do echo =$i >> /tmp/temporary_list_backup ; done
			quickpkg --include-config y --include-unmodified-config y $( cat /tmp/temporary_list_backup ) "$@"
		else
			rm -f /tmp/temporary_list_backup
			# shellcheck disable=SC2283
			for i in $( qlist -IvC ) ; do echo =$i >> /tmp/temporary_list_backup ; done
			quickpkg --include-config y --include-unmodified-config y $( cat /tmp/temporary_list_backup ) "$@"
		fi
	else
		if [[ ! -e "/tmp/temporary_list_backup" ]] ; then
			# shellcheck disable=SC2283
			for i in $( qlist -IvC ) ; do echo =$i >> /tmp/temporary_list_backup ; done
			quickpkg --include-config y --include-unmodified-config y $( cat /tmp/temporary_list_backup ) "$@"
		else
			rm -f /tmp/temporary_list_backup
			# shellcheck disable=SC2283
			for i in $( qlist -IvC ) ; do echo =$i >> /tmp/temporary_list_backup ; done
			quickpkg --include-config y --include-unmodified-config y $( cat /tmp/temporary_list_backup ) "$@"
		fi
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

cleanoutdated() {
	# function designed to clearout any outdated package using gentoolkit
	# the unconventional way here: we import /etc/portage/make.conf into current local function
	# we have 2 checks here: if usr/portage and usr/portage/packages really exist
	# we may never know what users do to their portage dirs in Gentoo system 
	checkmakeconf

	if [ -d "${PKGDIR}" ] ; then
		/usr/bin/eclean-pkg
	else
		eerror "No such directory ${PKGDIR}"
		echo "Please consider: mkdir ${PKGDIR}/"
		echo "chgrp portage ${PKGDIR}"
		exit 1
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

cleanlocalpkg() {
    # function to cleanup all local packages in /usr/portage/packages
    # it also includes deletion of /usr/portage/Packages
    # if we do not have any /usr/portage, there is no reason we should continue

	checkmakeconf

	if [ -d "${PKGDIR}" ] ; then
		rm -rf "${PKGDIR}"/* || exit 1
	else
		eerror "No such directory ${PKGDIR}"
		echo "Make sure you have this directory"
		echo "Also make sure you have the right GID:"
		echo "i.e.: chgrp portage ${PKGDIR}"
		exit 1
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

src-newuse() {
	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		eerror "If you continue, you continue at your own risk!"
		sleep 3
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -va --newuse --changed-use "$@"
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -va --newuse --changed-use "$@"
	fi
}

compilepkg() {
	# function to call a recompile of a package and save it to ${PKGDIR}"

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		eerror "If you continue, you continue at your own risk!"
		sleep 3
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -va "$@"
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -va "$@"
	fi
}

recompilepkg() {
	# function to call a recompile of a package and save it to ${PKGDIR}"

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		eerror "If you continue, you continue at your own risk!"
		sleep 3
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --oneshot -va "$@"
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --oneshot -va "$@"
	fi
}

recompileallpkg() {
	# function to recompile everything on the system and also save all the recompiled packages.

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are not allowed to run in --usermode, we propose using: avasile --devmode or --srcmode for this"
		exit 1
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -va $(qlist -IC)
		eerror "Warning: if there are packages that are not found, you must run: epkg update"
		eerror "If the error persists, force remove the package causing the corruption:"
		eerror "in --devmode: epkg remove <package-name>"
		eerror "in --srcmode: emerge --unmerge <package-name>"
		eerror "Then re-run the same command: epkg recompileallpkg"
	fi
}

autocompilepkg() {
	# function to call a recompile of a package and save it to ${PKGDIR}"

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		eerror "If you continue, you continue at your own risk!"
		sleep 3
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -v "$@"
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -v "$@"
	fi
}

autorecompilepkg() {
	# function to call a recompile of a package and save it to ${PKGDIR}"

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		eerror "If you continue, you continue at your own risk!"
		sleep 3
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --oneshot -v "$@"
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --oneshot -v "$@"
	fi
}

autorecompileallpkg() {
	# function to recompile everything on the system and also save all the recompiled packages.

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are not allowed to run in --usermode, we propose using: avasile --devmode or --srcmode for this"
		exit 1
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -v $(qlist -IC)
	fi
}

recompile-depend() {
    # function to recompile all the packages that directly depend on this package

    local exclude_packages=()
    local args=("$@")
    local new_args=()

    for ((i = 0; i < ${#args[@]}; i++)); do
        if [[ "${args[i]}" == "--exclude" ]]; then
            if [[ $((i + 1)) -lt ${#args[@]} ]]; then
                exclude_packages+=("${args[i + 1]}")
                i=$((i + 1))
            fi
        else
            new_args+=("${args[i]}")
        fi
    done

    if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]]; then
        eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
        eerror "If you continue, you continue at your own risk!"
        sleep 3
    fi

	# function to create a lock file in order to not be possibly overwritten by another epkg (auto) recompile-depend
    local temp_list="/tmp/epkg_temporary_list"
    exec 200>"$temp_list"
    flock -n 200 || { echo "Failed to acquire lock on $temp_list"; exit 1; }

    cat /dev/null > "$temp_list"
    equery d "${new_args[@]}" | awk '{print $1}' | sed -e 's/^/=/' >> "$temp_list"

    if [[ -s "$temp_list" ]]; then
        local exclude_str=""
        if [[ ${#exclude_packages[@]} -gt 0 ]]; then
            for pkg in "${exclude_packages[@]}"; do
                exclude_str+="--exclude ${pkg} "
            done
        fi
        EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --oneshot -va --keep-going $(cat "$temp_list") $exclude_str
    else
        echo "There are no packages that depend on given package(s)"
    fi

    rm -f "$temp_list" || exit 1
    flock -u 200
    exec 200>&-
}

recompile-depend-new() {
    # function to recompile all the new packages that directly depend on this package

    if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
        eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
        eerror "If you continue, you continue at your own risk!"
        sleep 3
    fi

	# function to create a lock file in order to not be possibly overwritten by another epkg (auto) recompile-depend
    local temp_list="/tmp/epkg_temporary_list"
    exec 200>"$temp_list"
    flock -n 200 || { echo "Failed to acquire lock on $temp_list"; exit 1; }

    cat /dev/null > "$temp_list"
    # shellcheck disable=SC2283
    for i in $(equery d "$@" | awk '{print $1}') ; do echo =${i} >> "$temp_list" ; done

    if [[ -s "$temp_list" ]] ; then
        EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --oneshot -va --keep-going $(cat "$temp_list")
    else
        echo "There are no packages that depend on given package(s)"
    fi

    rm -f "$temp_list" || exit 1
    flock -u 200
    exec 200>&-
}

autorecompile-depend() {
    # function to recompile all the packages that directly depend on this package with no confirmation

    local exclude_packages=()
    local args=("$@")
    local new_args=()

    for ((i = 0; i < ${#args[@]}; i++)); do
        if [[ "${args[i]}" == "--exclude" ]]; then
            if [[ $((i + 1)) -lt ${#args[@]} ]]; then
                exclude_packages+=("${args[i + 1]}")
                i=$((i + 1))
            fi
        else
            new_args+=("${args[i]}")
        fi
    done

    if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]]; then
        eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
        eerror "If you continue, you continue at your own risk!"
        sleep 3
    fi

	# function to create a lock file in order to not be possibly overwritten by another epkg (auto) recompile-depend
    local temp_list="/tmp/epkg_temporary_list"
    exec 200>"$temp_list"
    flock -n 200 || { echo "Failed to acquire lock on $temp_list"; exit 1; }

    cat /dev/null > "$temp_list"
    equery d "${new_args[@]}" | awk '{print $1}' | sed -e 's/^/=/' >> "$temp_list"

    if [[ -s "$temp_list" ]]; then
        local exclude_str=""
        if [[ ${#exclude_packages[@]} -gt 0 ]]; then
            for pkg in "${exclude_packages[@]}"; do
                exclude_str+="--exclude ${pkg} "
            done
        fi
        EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -v --oneshot --keep-going $(cat "$temp_list") $exclude_str
    else
        echo "There are no packages that depend on given package(s)"
    fi

    rm -f "$temp_list" || exit 1
    flock -u 200
    exec 200>&-
}

autorecompile-depend-new() {
    # function to recompile all the new packages that directly depend on this package with no confirmation

    if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
        eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
        eerror "If you continue, you continue at your own risk!"
        sleep 3
    fi

	# function to create a lock file in order to not be possibly overwritten by another epkg (auto) recompile-depend
    local temp_list="/tmp/epkg_temporary_list"
    exec 200>"$temp_list"
    flock -n 200 || { echo "Failed to acquire lock on $temp_list"; exit 1; }

    cat /dev/null > "$temp_list"
    # shellcheck disable=SC2283
    for i in $(equery d "$@" | awk '{print $1}') ; do echo =${i} >> "$temp_list" ; done

    if [[ -s "$temp_list" ]] ; then
        EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge -v $(cat "$temp_list")
    else
        echo "There are no packages that depend on given package(s)"
    fi

    rm -f "$temp_list" || exit 1
    flock -u 200
    exec 200>&-
}

# soon to be rewritten / deprecated
reinstall-depend() {
	# function to reinstall all new packages that directly depend on this package

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		eerror "If you continue, you continue at your own risk!"
		sleep 3
		cat /dev/null > /tmp/epkg_temporary_list
		# shellcheck disable=SC2283
		for i in $(equery d "$@" | awk '{print $1}') ; do echo =${i} >> /tmp/epkg_temporary_list ; done
		emerge -va $( cat /tmp/epkg_temporary_list )
		rm -f /tmp/epkg_temporary_list || exit 1
	else
		cat /dev/null > /tmp/epkg_temporary_list
		# shellcheck disable=SC2283
		for i in $(equery d "$@" | awk '{print $1}') ; do echo =${i} >> /tmp/epkg_temporary_list ; done
		emerge -va $( cat /tmp/epkg_temporary_list )
		rm -f /tmp/epkg_temporary_list || exit 1
	fi
}

autoreinstall-depend() {
	# function to reinstall all new packages that directly depend on this package

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		eerror "If you continue, you continue at your own risk!"
		sleep 3
		cat /dev/null > /tmp/epkg_temporary_list
		# shellcheck disable=SC2283
		for i in $(equery d "$@" | awk '{print $1}') ; do echo =${i} >> /tmp/epkg_temporary_list ; done
		emerge -v $( cat /tmp/epkg_temporary_list )
		rm -f /tmp/epkg_temporary_list || exit 1
	else
		cat /dev/null > /tmp/epkg_temporary_list
		# shellcheck disable=SC2283
		for i in $(equery d "$@" | awk '{print $1}') ; do echo =${i} >> /tmp/epkg_temporary_list ; done
		emerge -v $( cat /tmp/epkg_temporary_list )
		rm -f /tmp/epkg_temporary_list || exit 1
	fi
}

fetchsourcepkg() {
	# function to download the source of the program for development / patching purposes
	# the unconventional way here: we import /etc/portage/make.conf into current local function

	checkportdir

	# function to warn the regular user that he's doing something wrong
	# but still do it anyway.

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You are on --usermode, we propose using: avasile --devmode or --srcmode for this"
		sleep 3
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --fetchonly "$@"
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --fetchonly "$@"
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

fetchbinpkg() {
	# function to download the source of the program for development / patching purposes
	# the unconventional way here: we import /etc/portage/make.conf into current local function

	checkportdir

	# function to warn the regular user that he's doing something wrong
	# but still do it anyway.

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "Fetching binary package(s) from remote"
		sleep 2
		EMERGE_DEFAULT_OPTS="--getbinpkgonly --rebuilt-binaries" emerge --fetchonly "$@"
	else
		EMERGE_DEFAULT_OPTS="--getbinpkgonly --rebuilt-binaries" emerge --fetchonly "$@"
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

remove-orphans() {
	# The function calls 'emerge --depclean -a' which removes orphaned packages
	# Probably the most successful emerge algorythm ever made

	checkmakeconf

	emerge --depclean -a
}

buildinstall() {
	# Stands for build (-Bv) and install (-va with --getbinpkg)
	# Also regenerates the binhost Packages file

	if [[ -z "$@" ]] ; then
		eerror "You have not specified any package to build & install"
		echo " "
		exit 1
	fi

	checkportdir

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You cannot run buildpkgonly from the user profile!"
		exit 1
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --with-bdeps=y -Bva "$@"
		EMERGE_DEFAULT_OPTS="--getbinpkg --rebuilt-binaries" emerge -av "$@"
		emaint -f binhost
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

autobuildinstall() {
	# Stands for build (-Bv) and install (-va with --getbinpkg) automatically
	# Also regenerates the binhost Packages file

	if [[ -z "$@" ]] ; then
		eerror "You have not specified any package to build & install"
		echo " "
		exit 1
	fi

	checkportdir

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You cannot run buildpkgonly from the user profile!"
		exit 1
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --with-bdeps=y -Bv "$@"
		EMERGE_DEFAULT_OPTS="--getbinpkg --rebuilt-binaries" emerge -v "$@"
		emaint -f binhost
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

buildpkgonly() {
	# function to only build 1 or more packages based on input
	# works as: epkg buildpkg-only <something>

	checkportdir

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You cannot run buildpkgonly from the user profile!"
		exit 1
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --with-bdeps=y -Bva "$@"
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

autobuildpkgonly() {
	# function to only build 1 or more packages based on input
	# works as: epkg autobuildpkg-only <something>

	checkportdir

	if [[ "$(readlink -f "/etc/portage/make.conf")" = "/opt/argentws-build/conf/intel/portage/make.conf.amd64-user" ]] ; then
		eerror "You cannot run buildpkgonly from the user profile!"
		exit 1
	else
		EMERGE_DEFAULT_OPTS="--rebuilt-binaries" emerge --with-bdeps=y -Bv "$@"
	fi

	# regenerating environment here is a must!
	env-update && source /etc/profile
}

syncportageconfig() {
	# syncing with the latest updates on our argent gentoo configs

	pushd /opt/argentws-build > /dev/null 2>&1 || return
	echo ">>> Syncing 'portage config' into '/etc/portage' "
	echo "Git pulling latest modifications. Please, stand by..."

	if [[ ! -e .git ]] ; then
		echo -e ""
		eerror "You do not have any connection with the Argent main server"
		eerror "Establish a .git connection to the main Argent EPKG server"
		eerror "Or use "$ENABLE_COLOR"avasile --help"$DISABLE_COLOR" to switch stance"
		eerror "Ignoring local changes"
		echo -e ""
	else
		git pull
	fi

	echo "=== Sync completed for 'portage config'"

	popd > /dev/null 2>&1 || return
}

argentsync() {
	if [[ "${EPKG_DISTRO_SET}" == "argent" ]]; then
		syncrepos
		syncportageconfig
	fi
	echo ""
}
