#!/bin/bash

# File: src-maintenance
#
# Description: This file simplifies managing $HOME/src
#
# Package: DarkFeather/HomeDir
# Copyright: WTFPL
# # Author: DarkFeather <ircs://aninix.net:6697/DarkFeather>

source /opt/aninix/Uniglot/Bash/header
conffile="$HOME/.$(basename "$0").conf"
unset noconfirm
mkdir -p $HOME/src

function usage() {
    ### Write the usage
    ### param retcode: the return code
    retcode="$1"
    echo "Usage: $0    # List the state of clones by default"
    echo "       $0 -h # Helptext"
    echo "       $0 -c # Clone everything in the conf file."
    echo "       $0 -r # Remove the spurious clones"
    echo "       $0 -w # Helptext"
    echo "Add -v to increase verbosity."
    echo "Add -y to skip confirmations."
    exit $retcode
}

function cloneList() {
    ### git-clone all the tracked repos.
    cat "$conffile" | while read line; do
        dir="$(echo "$line" | cut -f 1 -d ' ')"
        gitrepo="$(echo "$line" | cut -f 2 -d ' ')"
        cd $HOME
        mkdir -p "$(dirname "$dir")"
        if [ ! -d "$dir" ]; then
            git clone "$gitrepo" "$dir"
        else
            cd "$dir"
            git pull;
        fi
    done
}

function writeOutList() {
    ### Write out the list of clones
    cd $HOME
    for clone in `find . -type d -name .git | sed 's/\.git$//'`; do
        cd "$clone"
        printf "$(echo "$clone" | sed 's#^\.\/##' | sed 's/\/$//') "
        git config remote.origin.url
        cd $HOME
    done | sort | uniq | grep -E -iv 'aninix|gitea@localhost|/srv/foundation|homedir' > "$conffile"
    exit $?
}

### Main
if [[ "$(basename "$0")" == "src-maintenance" ]]; then
    while getopts 'chrwv' OPTION; do
        case "$OPTION" in
            c) cloneList; ;;
            h) echo This tool simplifies clone maintenance; usage 0 ;;
            w) writeOutList ;;
            v) set -x ;;
            y) noconfirm=1 ;;
            *) usage 1 ;;
        esac
    done
fi
