#!/usr/bin/env bash
# Copyright (C) 2011-2012 Nicolás Reynolds <fauno@parabola.nu>
# Copyright (C) 2012-2013, 2015, 2017 Luke Shumaker <lukeshu@sbcglobal.net>
#
# If you don't see m4_include(...) below, but see function definitions
# for msg() et al., then this is a generated file, and contains some
# code from librelib.  See the source distribution for full copyright
# information.
#
# License: GNU GPLv3+
#
# This program 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.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Performs chroot cleanup smartly, it only removes the unneeded packages or
# leaves you with a cleansystem
#
# See: HOOKPREBUILD

set -eE

DRYRUN=${DRYRUN:-false}

# Statically include various library routines to avoid having
# dependencies on outside files.
[[ -n ${TEXTDOMAIN:-}    ]] || export TEXTDOMAIN='libretools'
[[ -n ${TEXTDOMAINDIR:-} ]] || export TEXTDOMAINDIR='/usr/share/locale'

if type gettext &>/dev/null; then
	_() { gettext "$@"; }
else
	_() { echo "$@"; }
fi
# Begin chcleanup.lib ##########################################################
_l () 
{ 
    TEXTDOMAIN='librelib' TEXTDOMAINDIR='/usr/share/locale' "$@"
}
plain () 
{ 
    local mesg;
    mesg="$(_ "$1")";
    shift;
    printf "${BOLD}    ${mesg}${ALL_OFF}\n" "$@" 1>&2
}
msg () 
{ 
    local mesg;
    mesg="$(_ "$1")";
    shift;
    printf "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" 1>&2
}
msg2 () 
{ 
    local mesg;
    mesg="$(_ "$1")";
    shift;
    printf "${BLUE}  ->${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" 1>&2
}
error () 
{ 
    local mesg;
    mesg="$(_ "$1")";
    shift;
    printf "${RED}==> ERROR:${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" 1>&2
}

# End chcleanup.lib ############################################################

if [[ ! -f /.arch-chroot ]] && ! ${DRYRUN}; then
	error "(chcleanup): Must be run inside of a chroot"
	exit 1
fi

# Note: the in-chroot pkgconfdir is non-configurable, this is
# intentionally hard-coded.
source /etc/libretools.d/chroot.conf
# If we're running makepkg
if [[ -f PKGBUILD ]]; then
	CARCH="$(. /etc/makepkg.conf; printf '%s' "$CARCH")"
	export CARCH
	source ./PKGBUILD
	CHROOTEXTRAPKG+=("${depends[@]}"
	                 "${makedepends[@]}"
	                 "${checkdepends[@]}")
fi

msg "Cleaning chroot..."

# Sync the local repo with pacman
cp /repo/repo.db /var/lib/pacman/sync/repo.db

# Setup the temporary directory
TEMPDIR="$(mktemp --tmpdir -d "${0##*/}.XXXXXXXXXX")"
trap "rm -rf -- $(printf '%q' "$TEMPDIR")" EXIT

cp -a /var/lib/pacman/sync "${TEMPDIR}/"
pkglist="${TEMPDIR}"/pkglist.txt

# Get the full list of packages needed by dependencies, including the base system
msg2 "Creating a full list of packages..."
pacman -b "${TEMPDIR}" \
       -Sp --print-format "%n" base-devel "${CHROOTEXTRAPKG[@]}" >"$pkglist" || {
	ret=$?
	error "Could not create a full list of packages, exiting."
	plain "This is likely caused by a dependency that could not be found."
	exit $ret
}

# Diff installed packages against a clean chroot then remove leftovers
packages=($(comm -23 <(pacman -Qq | sort -u) \
                     <(sort -u "${pkglist}")))

if [[ ${#packages[@]} = 0 ]]; then
	msg2 "No packages to remove"
else
	msg2 "Removing %d packages" ${#packages[@]}

	if ${DRYRUN}; then
		echo "${packages[*]}"
	else
		# Only remove leftovers, -Rcs removes too much
		pacman --noconfirm -Rn "${packages[@]}"
	fi
fi
