#!/usr/bin/env bash
# Copyright (C) 2010-2011 Joshua Ismael Haase Hernández (xihh) <hahj87@gmail.com>
# Copyright (C) 2010-2012 Nicolás Reynolds <fauno@parabola.nu>
# Copyright (C) 2012-2014, 2017 Luke Shumaker <lukeshu@parabola.nu>
#
# License: GNU GPLv3+
#
# This file is part of Parabola.
#
# Parabola is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Parabola is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Parabola. If not, see <http://www.gnu.org/licenses/>.

. "$(librelib messages)"

usage() {
	print "Usage: %s [-h] PKGNAME [PKGNAME2 PKGNAME3...]" "${0##*/}"
	print "Downloads packages from the AUR, and does basic freedom checks."
	echo
	prose "This script will download packages from AUR to the current
	       directory and check their license for nonfree issues.  This does
	       not mean that they are free; they may be incorrectly labeled, or
	       have other freedom issues.  It's a tool to help Parabola
	       packagers, not to help users install things directly from AUR."
}

main() {
	while getopts 'h' arg; do
		case $arg in
			h) usage; return $EXIT_SUCCESS;;
			*) usage >&2; return $EXIT_INVALIDARGUMENT;;
		esac
	done
	if [[ $# -lt 1 ]]; then
		usage >&2
		return $EXIT_INVALIDARGUMENT
	fi

	. "$(librelib conf)"
	load_conf libretools.conf libretools DIFFPROG || exit

	local startdir=$PWD
	local missing_deps=()
	local ret=$EXIT_SUCCESS
	local pkg
	local copy_new
	local copy_old
	for pkg in "$@"; do
		pkg="${pkg%%[<>=]*}" # remove the version
		msg "Processing package: %s" "$pkg"
		copy_new="$startdir/$pkg"
		copy_old=

		if [[ -f "${copy_new}/PKGBUILD" ]]; then
			warning "%s already exists, will compare with new version." "$pkg"

			# Store our copy of the PKGBUILD dir
			copy_old=$copy_new
			copy_new="$(mktemp --tmpdir -d "aur-${pkg}.new.XXXX")/$pkg"
			cd "${copy_new%/*}"
		fi

		msg2 "Downloading"
		local url="https://aur.archlinux.org/packages/${pkg:0:2}/$pkg/$pkg.tar.gz"
		set -o pipefail
		if ! wget -O- -q "$url" | bsdtar xf -; then
			ret=$((ret|EXIT_FAILURE))
			error "Couldn't get %s" "$pkg"
			continue
		fi
		set +o pipefail

		if [[ -n $copy_old ]]; then
			msg2 "Diffing files"
			cd "$copy_new"

			# Diff all files with our difftool
			local diffed=false
			for file in *; do
				if ! cmp -s "${copy_old}/${file}" "${copy_new}/${file}" ; then
					warning "%s != %s" "${copy_old}/${file}" "${copy_new}/${file}"
					diffed=true
					"${DIFFPROG}" "${copy_old}/${file}" "${copy_new}/${file}"
				fi
			done
			if $diffed; then
				read -rp "Press enter to continue."
			fi

			# Go back to our copy to continue working
			cd "$copy_old"
			rm -rf -- "${copy_new%/*}"
		else
			cd "$copy_new"
		fi

		load_PKGBUILD

		################################################################

		pkgbuild-check-nonfree -c
		pkgbuild-summarize-nonfree $?

		################################################################

		local _deps=(
			# depends
			"${depends[@]}" "${makedepends[@]}" "${checkdepends[@]}"
			# mksource depends
			"${mkdepends[@]}"
		)
		local _dep
		msg2 "Checking dependencies"
		for _dep in "${_deps[@]}"; do
			_dep=${_dep/[<>=]*/}
			if ! is_built "$_dep"; then
				if ! pacman -Sddp "$_dep" &>/dev/null ; then
					plain "%s: will be downloaded from AUR" "$_dep"
					missing_deps+=("$_dep")
				fi
			else
				plain "%s: is on repos" "$_dep"
			fi
		done
		cd "$startdir"
	done

	if [[ ${#missing_deps[*]} -gt 0 ]]; then
		msg "Retrieving missing deps: %s" "${missing_deps[*]}"
		"$0" "${missing_deps[@]}"
		ret=$((ret|$?))
	fi
	return $ret;
}

main "$@"
