#!/bin/bash

# File: pruneable-branches
#
# Description: This file helps find pruneable branches.
#
# Package: AniNIX/ShadowArch
# Copyright: WTFPL
#
# Author: DarkFeather <ircs://irc.aninix.net:6697/DarkFeather>

source /usr/share/git/git-prompt.sh

function checkBranches() {
    ### Check the local branches for any potential cleanup
    ### param whitelist: branches to ignore
    ### param remove (optional): should we do the cleanup.

    unset removeable whitelist
    whitelist="$1"
    removeable="$2"


    if [ -n "$whitelist" ]; then
        whitelist="${whitelist}|$(__git_ps1 '%s')"
    else
        whitelist="$(__git_ps1 '%s')"
    fi

    # Iterate on branches
    for branch in $(git branch -l | grep -v "$whitelist"); do
        branchHead="$(git rev-parse "$branch")"

        # If the branch is in the log for the current branch, it's actionable.
        if (git log | grep "$branchHead" 1>/dev/null); then
            if [ -n "$removeable" ]; then
                git branch -d "$branch"
            else
                echo "$branch has been merged."
            fi

            # If remote also exists, then we should deal with that too.
            if (git branch -r -l | grep "$branch" 1>/dev/null); then
                if [ -n "$removeable" ]; then
                    git push --delete origin "$branch"
                else
                    echo ' * Remote branch can be pruned.'
                fi
            fi

            if [ -z "$removeable" ]; then
                git log -n1 "$branch"
            fi
        fi
    done
}

function Usage() {
    ### Show help
    echo "WARNING: This should only be run on the protected branch."
    echo "Usage: $0 -h"
    echo "       $0"
    echo "       $0 -r [ -w branch,branch... ]"
    echo Add -w to include a comma-separated list of whitelisted branches.
    echo i.e. -w release,develop
}


function main() {
    ### Main operation
    unset removeable
    whitelist=""
    while getopts 'hrvw:' OPTION; do
        case "$OPTION" in
            h) Usage 0 ;;
            r) removeable=1 ;;
            v) set -x ;;
            w) whitelist="$( echo "${OPTARG}" | sed 's/,$//' | tr ',' '|')" ;;
            *) Usage 1 ;;
        esac
    done

    checkBranches "$whitelist" $removeable
}

# Allow sourcing
if [ "$(basename "$0")" == "pruneable-branches" ]; then
    main $@
fi
