#!/bin/bash
m=
if [[ -n $1 ]]; then
    if [[ $1 = -h* ]]; then
        echo "Usage: $(basename "$0") [-m] [BRANCH]"
        echo
        echo "Interactively delete branches merged into BRANCH (the current branch by default)"
        echo "Options:"
        echo "  -m      Include master, devel, upstream, latest, and main in list of branches"
        exit 0
    fi
    if [[ $1 = -m ]]; then
        m=1
        shift
    fi
    if [[ -n $1 ]]; then
        git checkout "$1" || exit $?
    fi
fi

branches=$(git branch --list --merged | grep -v '^[*+]')
if [[ ! $m ]]; then
    branches=$(grep -Ev ' (master|devel|upstream|latest|main)$' <<<"$branches")
fi

if [[ -z $branches ]]; then
    echo "No choices"
    exit 1
fi

echo "Select a merged branch to delete"
select b in '<DONE>' $branches; do
    if [[ $b = '<DONE>' ]]; then
        break
    fi
    git branch --delete "$b"
done
