which apt >/dev/null || return 0

addalternative() {
	sudo update-alternatives --install /usr/bin/$1 $1 "$(which "$1$2")" 1
}

snapinstall() {
	sudo snap install "$@" && refreshSetup
}

alias aptupdate='sudo apt-get update'
alias aptremove='sudo apt-get remove'
alias aptpurge='sudo apt-get purge --autoremove'
alias aptclean='sudo apt-get clean && sudo apt-get autoremove'
upgrade() {
	if test -x /usr/bin/pkcon
	then sudo pkcon update
	else sudo apt update && sudo apt upgrade
	fi
	sudo snap refresh
	flatpak update -y
	sudo npm update -g
	# npm -g outdated --parseable=true | cut -d : -f 4 | xargs -n 1 npm -g install
}

uma() {
	if test "$1"
	then printf 'y\nj\na' | umake "$1" "$2" "/opt/${3:-$2}"
	else
		uma ide idea-ultimate idea
		uma android android-studio android/android-studio && yes | /opt/android/sdk/tools/bin/sdkmanager --licenses && pathadd /opt/android/sdk/tools/bin /opt/android/sdk/platform-tools && sudo apt install qemu-kvm && sudo adduser janek kvm
		test -d "/opt/vscode" && uma ide visual-studio-code vscode
	fi
}

alias aptinstall='sudo apt-get install'
aptinstalls() {
	apt-cache show "$1" | grep --color=never '\(Version\|Description\):'
	aptinstall "$@"
}
aptinstalli() {
	apt download $1
	sudo dpkg --ignore-depends=$2 -i $1*.deb
}

if which add-apt-repository >/dev/null; then
	alias aptrepo='sudo add-apt-repository'
	_aptrepo_n="$(add-apt-repository --help | grep -- "-n")"
	aptrepon() {
		test $_aptrepo_n && aptrepo -y -n "$@" || aptrepo -y "$@"
	}
	aptrepos() {
		for repo in "$@"
		do aptrepon $repo
		done
		aptupdate
	}
	aptrepoinstall() {
		aptrepo -yu $1
		if (( $# > 1 ))
		then aptinstall "${@:2}"
		else aptinstall "${1##*/}"
		fi
	}
fi

# Gets the download url for the latest release of a package provided via GitHub Releases
# Usage: ghrelease USER REPO [PATTERN]
ghrelease() {
	result=$(curl -s "https://api.github.com/repos/$1/$2/releases/latest" | grep -o "http.*${3:-deb}" | awk '{ print length(), $0}' | sort -n | cut -d' ' -f2-)
	echo "$result" | command grep amd64 || echo "$result"
}

# Installs a local or remote(http/https) deb package and removes it after installation
installdeb() {
	loc="/tmp/install.deb"
	case $1 in
	http*) wget -O "$loc" $1;;
	*) loc="$1";;
	esac
	sudo dpkg -i "$loc" "${@:2}" && sudo apt -f install && rm "$loc"
}

installgh() {
	installdeb $(ghrelease "$@")
}

# Downloads all dependencies of a package into the current directory
download-debs() {
	apt-get download $1 && apt-cache depends -i $1 | awk '/Depends:/ {print $2}' | xargs apt-get download
}

