#!/data/data/com.itsaky.androidide/files/usr/bin/bash
set -eu

# Setup TERMUX_APP_PACKAGE_MANAGER
source "/data/data/com.itsaky.androidide/files/usr/bin/termux-setup-package-manager" || exit 1

MIRROR_BASE_DIR="/data/data/com.itsaky.androidide/files/usr/etc/termux/mirrors"

show_help() {
	local cache_size
	local cache_dir=""
	if [ "$TERMUX_APP_PACKAGE_MANAGER" = "apt" ]; then
		cache_dir="/data/data/com.itsaky.androidide/cache/apt/archives"
	elif [ "$TERMUX_APP_PACKAGE_MANAGER" = "pacman" ]; then
		cache_dir="/data/data/com.itsaky.androidide/files/usr/var/cache/pacman/pkg"
	fi
	cache_size=$(du -sh "$cache_dir" 2>/dev/null | cut -f1)

	echo 'Usage: pkg [--check-mirror] command [arguments]'
	echo
	echo 'A tool for managing packages.'
	echo '  --check-mirror forces a re-check of availability of mirrors'
	echo
	echo 'Commands:'
	echo
	echo '  autoclean            - Remove all outdated packages from .deb package'
	echo '                         cache.'
	echo
	echo '  clean                - Remove all packages from .deb package cache.'
	[ -n "$cache_size" ] && echo "                         Using $cache_size now."
	echo
	echo '  files <packages>     - Show all files installed by packages.'
	echo
	echo '  install <packages>   - Install specified packages.'
	echo
	echo '  list-all             - List all packages available in repositories.'
	echo
	echo '  list-installed       - List installed packages.'
	echo
	echo '  reinstall <packages> - Reinstall specified installed packages at the'
	echo '                         latest version.'
	echo
	echo '  search <query>       - Search package by query, for example by name or'
	echo '                         description part.'
	echo
	echo '  show <packages>      - Show basic metadata, such as dependencies.'
	echo
	echo '  uninstall <packages> - Uninstall specified packages. Configuration files'
	echo '                         will be left intact.'
	echo
	echo '  upgrade              - Upgrade all installed packages to the latest'
	echo '                         version.'
	echo
	exit 1
}

check_mirror() {
	local mirror="${1%/}"
	local timeout="${2-5}"

	timeout "$((timeout + 1))" curl \
		--head \
		--fail \
		--connect-timeout "$timeout" \
		--location \
		--user-agent "Termux-PKG/2.0 mirror-checker (termux-tools 1.30.2) Termux (com.itsaky.androidide; install-prefix:/data/data/com.itsaky.androidide/files/usr)" \
		"$mirror/dists/stable/Release" >/dev/null 2>&1
}

hostname() {
	echo "$1" | awk -F'[/:]' '{print $4}'
}

last_modified() {
	local mtime
	local now

	mtime=$(date -r "$1" '+%s')
	now=$(date '+%s')
	echo $((now - mtime))
}

has_repo() {
	# Check if root-repo or x11-repo are installed
	repo="$1"

	if [ -f "/data/data/com.itsaky.androidide/files/usr/etc/apt/sources.list.d/$repo.list" ]; then
		echo true
	else
		echo false
	fi
}

get_mirror_url() {
	source "$1"
	echo $MAIN
}

get_mirror_weight() {
	source "$1"
	if [[ ! "$WEIGHT" =~ ^[0-9]+$ ]]; then
		echo "[!] invalid weight in mirror $1" > /dev/stderr
		exit
	fi
	echo $WEIGHT
}

select_mirror() { :; }

update_apt_cache() {
	local current_host
	current_host=$(sed -nE -e 's|^\s*deb\s+https?://(.+)\s+stable\s+main$|\1|p' /data/data/com.itsaky.androidide/files/usr/etc/apt/sources.list | head -n 1)

	if [ -z "$current_host" ]; then
		# No primary repositories configured?
		apt update
		return
	fi

	local metadata_file
	metadata_file=$(
		list_prefix=$(echo "$current_host" | sed 's|/|_|g')
		arch=$(dpkg --print-architecture)
		echo "/data/data/com.itsaky.androidide/files/usr/var/lib/apt/lists/${list_prefix}_dists_stable_main_binary-${arch}_Packages" | sed 's|__|_|g'
	)

	if [ ! -e "/data/data/com.itsaky.androidide/cache/apt/pkgcache.bin" ] || [ ! -e "$metadata_file" ]; then
		apt update
		return
	fi

	local cache_modified
	cache_modified=$(last_modified "/data/data/com.itsaky.androidide/cache/apt/pkgcache.bin")

	local sources_modified
	sources_modified=$(last_modified "/data/data/com.itsaky.androidide/files/usr/etc/apt/sources.list")

	if (( sources_modified <= cache_modified )) || (( cache_modified > 1200 )); then
		apt update
	fi
}

force_check_mirror=false
if [ "${1-}" = "--check-mirror" ]; then
    force_check_mirror=true
    shift 1
fi

if [[ $# = 0 || $(echo "$1" | grep "^h") ]]; then
	show_help
fi

CMD="$1"
shift 1
ERROR=false

case "$TERMUX_APP_PACKAGE_MANAGER" in
	apt)
		case "$CMD" in
			f*) dpkg -L "$@";;
			sh*|inf*) apt show "$@";;
			add|i*) select_mirror; update_apt_cache; apt install "$@";;
			autoc*) apt autoclean;;
			cl*) apt clean;;
			list-a*) apt list "$@";;
			list-i*) apt list --installed "$@";;
			rei*) apt install --reinstall "$@";;
			se*) select_mirror; update_apt_cache; apt search "$@";;
			un*|rem*|rm|del*) apt remove "$@";;
                        upd*) select_mirror; apt update;;
			upg*) select_mirror; apt update; apt full-upgrade "$@";;
			*) ERROR=true;;
		esac;;
	pacman)
		case "$CMD" in
			f*) pacman -Ql "$@";;
			sh*|inf*) pacman -Qi "$@";;
			add|i*) pacman -Sy --needed "$@";;
			autoc*) pacman -Sc;;
			cl*) pacman -Scc;;
			list-a*) pacman -Sl "$@";;
			list-i*) pacman -Q "$@";;
			rei*) pacman -S "$@";;
			se*) pacman -Sys "$@";;
			un*|rem*|rm|del*) pacman -Rcns "$@";;
                        upd*) pacman -Sy "$@";;
			upg*) pacman -Syu "$@";;
			*) ERROR=true;;
		esac;;
esac

if $ERROR; then
	echo "Unknown command: '$CMD' (run 'pkg help' for usage information)"; exit 1
fi
