#!/data/data/com.bai.diple.ide/files/usr/bin/bash
set -eu

# Root Check
if [[ "$(id -u)" == "0" ]]; then
	echo "Error: Cannot run 'pkg' command as root"
	exit 1
fi

show_help() {
	local cache_size
	local cache_dir="/data/data/com.bai.diple.ide/cache/apt/archives"
	cache_size=$(du -sh "$cache_dir" 2>/dev/null | cut -f1)

	echo 'Usage: pkg command [arguments]'
	echo
	echo "A tool for managing apt packages."
	echo
	echo 'Commands:'
	echo
	echo "  autoclean            - Remove all outdated packages from apt cache."
	echo
	echo "  clean                - Remove all packages from apt 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
	echo "  update               - Update apt databases from configured"
	echo '                         repositories.'
	echo
	exit 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.bai.diple.ide/files/usr/etc/apt/sources.list.d/$repo.list" ]; then
		echo true
	else
		echo false
	fi
}

update_apt_cache() {
	local cache_modified
	cache_modified=$(last_modified "/data/data/com.bai.diple.ide/cache/apt/pkgcache.bin")

	if (( cache_modified > 1200 )); then
		apt update
	fi
}

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

CMD="$1"
shift 1
ERROR=false

case "$CMD" in
	f*) dpkg -L "$@";;
	sh*|inf*) apt show "$@";;
	add|i*) 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*) update_apt_cache; apt search "$@";;
	un*|rem*|rm|del*) apt remove "$@";;
                    upd*) apt update;;
	up|upg*) apt update; apt full-upgrade "$@";;
	*) ERROR=true;;
esac

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