#!/bin/bash
# -*- coding: utf-8; mode: sh; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=sh:et:sw=4:ts=4:sts=4

# Note:
# This script is sourced by the mpbb wrapper script.
# Do not execute this directly!

cleanup-usage() {
    # "prog" is defined in mpbb-help.
    # shellcheck disable=SC2154
    cat <<EOF
usage: $prog [<global opts>] cleanup

Clean up after a build.

Run \`$prog help' for global options and a list of other subcommands.
EOF
}

cleanup() {
    # if this is the very first build, selfupdate did not install port yet
    # $option_prefix is set in mpbb
    # shellcheck disable=SC2154
    if [ ! -e "${option_prefix}/bin/port" ]; then
        echo "---> Skipping cleanup"
        echo "port not installed at ${option_prefix}/bin/port"
        return
    fi

    echo "----> Deactivating ports"
    # $option_prefix is set by mpbb
    # shellcheck disable=SC2154
    if [ -n "$("${option_prefix}/bin/port" -q installed active)" ]; then
        "${option_prefix}/bin/port" -fp deactivate active
    fi
    echo
    echo "----> Uninstalling obsolete ports"
    # $thisdir is set by mpbb and points to the directory in which this script resides
    # shellcheck disable=SC2154
    "${option_prefix}/bin/port-tclsh" "${thisdir}/tools/uninstall-old-ports.tcl"
    echo
    echo "----> Deleting distfiles"
    find "${option_prefix}/var/macports/distfiles" -type f -mtime +1 -print -delete | sed -E 's/^/Deleting distfile /'
    find "${option_prefix}/var/macports/distfiles" -type d -mindepth 1 -empty -print -delete | sed -E 's/^/Deleting directory /'
    echo
    for dir in build logs; do
        echo "----> Deleting ${dir}"
        ports="$(find "${option_prefix}/var/macports/${dir}" -name '.*' -prune -o -depth 2 -type d -print | sed 's,^.*/,,' | sort -fu)"
        for port in ${ports}; do
            echo "Deleting ${dir} for ${port}"
            rm -rf "${option_prefix}/var/macports/${dir}"/*/"${port}"
        done
        rm -rf "${option_prefix}/var/macports/${dir}"/*
        echo
    done
  }