#!/bin/bash
###
# pkgclean - Tidy up a PKGBUILD directory
# This program is a part of pkgtools

# Copyright (C) 2010-2011 Daenyth <Daenyth+Arch _AT_ gmail _DOT_ com>
#
# Pkgtools 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 2
# of the License, or (at your option) any later version.
#
# Pkgtools 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
##

PKGTOOLS_DIR='/usr/share/pkgtools/'
CONFIG_DIR='/etc/pkgtools/'
readonly MYVERSION=1.1
readonly PROGNAME=$(basename $0)

if [ -r "$PKGTOOLS_DIR/functions" ]; then
    source "$PKGTOOLS_DIR/functions"
else
    printf "Unable to source function file!\n" >&2
    exit 1
fi
VERBOSE=0
LIST=1

clean_makedirs () {
    vmsg "Cleaning leftover makepkg directories... "
    for dir in pkg src; do
        if [[ -d "$dir" ]]; then
            if (( LIST )); then
                echo "$dir/"
            else
                rm -rf "$dir"
            fi
        fi
    done
    vmsg "Done.\n"
}

clean_srcpkgs () {
    . /etc/makepkg.conf
    vmsg "Cleaning source packages... "
    SRCPKGS=(*"$SRCEXT")
    if [[ ! -f "${SRCPKGS[0]}" ]]; then
        vmsg "Empty.\n"
        return 0
    fi
    if (( LIST )); then
        printf '%s\n' "${SRCPKGS[@]}"
        return 0
    fi
    if [[ -n "$SRCDEST" ]]; then
        vmsg "Moving to \$SRCDEST... "
        mv -f "${SRCPKGS[@]}" "$SRCDEST"
    elif [[ "$PURGE" ]]; then
        vmsg "Purging... "
        rm -f "${SRCPKGS[@]}"
    else
        vmsg "Aborted.\n"
        return 1
    fi
    vmsg "Done.\n"
}

clean_pkgs () {
    . /etc/makepkg.conf
    vmsg "Cleaning built packages... "
    PKGS=(*"$PKGEXT")
    if [[ ! -f "${PKGS[0]}" ]]; then
        vmsg "Empty.\n"
        return 0
    fi
    if (( LIST )); then
        printf '%s\n' "${PKGS[@]}"
        return 0
    fi
    if [[ -n "$PKGDEST" ]]; then
        vmsg "Moving to \$PKGDEST... "
        mv -f "${PKGS[@]}" "$PKGDEST"
    elif [[ "$PURGE" ]]; then
        vmsg "Purging... "
        rm -f "${PKGS[@]}"
    else
        vmsg "Aborted.\n"
        return 1
    fi
    vmsg "Done.\n"
}

clean_downloads () {
    . PKGBUILD
    vmsg "Cleaning downloaded source files... "
    for file in "${source[@]}" "$install"; do
        if echo "$file" | grep -q '://'; then
            file=$(get_filename "$file")
            if [[ -f "$file" ]]; then
                if (( LIST )); then
                    echo "$file"
                else
                    rm -f "$file"
                fi
            fi
        fi
    done
    vmsg "Done.\n"
}

clean_cruft () {
    [[ "$PURGE" ]] || return 1
    vmsg "Purging all non-required files... "

    . PKGBUILD
    declare -A noremove
    for file in "${source[@]}" "$install" "$changelog" PKGBUILD; do
        [[ -z "$file" ]] && continue
        file=$(get_filename "$file")
        noremove["$file"]=1
    done

    for file in *; do
        if [[ "${noremove["$file"]}" != 1 ]]; then
            if (( LIST )); then
                echo "$file"
            else
                rm -f "$file"
            fi
        fi
    done
    vmsg "Done.\n"
}

clean_all () {
    clean_makedirs
    clean_pkgs
    clean_srcpkgs
    clean_downloads
    clean_cruft
}

# Copied from makepkg
# extract the filename from a source entry
get_filename() {
    # if a filename is specified, use it
    local filename="${1%%::*}"
    # if it is just an URL, we only keep the last component
    echo "${filename##*/}"
}

usage () {

#           |--------------------------------------------------------------------------------| 80 Characters
        msg "%s version %s -- Clean files from a PKGBUILD directory\n" "$PROGNAME" "$MYVERSION"
        msg "Usage: %s [OPTIONS]\n" "$PROGNAME"
        msg "  -c --clean   - Clean the directory of unneeded files.\n"
        msg "                 The default is to list files to be cleaned.\n"
        msg "  -h --help    - Print this help.\n"
        msg "  --purge      - Delete *ALL* non-required files.\n"
        msg "  -v --verbose - Enable verbose output.\n"
        msg "\nWARNING: This tool can be very destructive. Use at your own risk!\n"
#           |--------------------------------------------------------------------------------| 80 Characters
        quit "${1:-0}"
}


while [[ $# > 0 ]]; do
    case "$1" in
        -c|--clean) LIST=0 ;;
        -h|--help) usage   ;;
        --purge) PURGE=1   ;;
        -v|--verbose)
            VERBOSE=1
            ;;
    esac
    shift
done

[[ -f PKGBUILD ]] || die 1 "Not a PKGBUILD dir!\n"

clean_all

# vim: set ts=4 sw=4 et :
