#!/bin/bash

# File: active-projects
#
# Description: This file finds active projects.
#
# Package: AniNIX/ShadowArch
# Copyright: WTFPL
# Author: DarkFeather <ircs://aninix.net:6697/DarkFeather

targetdir="$PWD"
unset aninix

function usage() {
    ### Write the usage
    ### param retcode: the return code
    retcode="$1"
    echo "Usage: $0        # List the state of clones found under this directory"
    echo "       $0 -t dir # Search the directory"
    echo "       $0 -A     # AniNIX repos only."
    echo "       $0 -h     # Helptext"
    echo "Add -v to increase verbosity."
    exit $retcode
}

function showProject() {
    printf "$(echo "${founddir}" | sed 's#/.git##' ) "
    git config remote.origin.url
}


function findActiveProjects() {
    ### Find the active projects

    # Delimit by newline
    IFS="
    "

    # Iterate on each directory
    for founddir in `find "${targetdir}" -type d -name .git`; do
        cd "${founddir}/.."

        # Test for branches
        (git branch -l ; git branch -r -l) | grep -vE 'master|main' &>/dev/null
        if [ $? -eq 0 ]; then
            showProject
            continue
        fi

        # Test for stashes
        if [[ `git stash list | wc -l` -ne 0 ]]; then
            showProject
            continue
        fi

        # Test for status
        if [[ `git status | grep -cE "Your branch is up to date with 'origin/[a-zA-Z0-9]*'\.$|^nothing to commit, working tree clean$"` -ne 2 ]]; then
            showProject
            continue
        fi

        cd "$OLDPWD"
    done
}

### Main
if [[ "$(basename "$0")" == "active-projects" ]]; then
    while getopts 'At:v' OPTION; do
        case "$OPTION" in
            A) aninix=1 ;;
            t) targetdir="${OPTARG}" ;;
            v) set -x ;;
            *) usage 1 ;;
        esac
    done

    findActiveProjects | if [ -n "$aninix" ]; then grep aninix.net; else cat; fi
fi
