#!/usr/bin/env bash
# Finds and verifies signatures of git repositories in specified dir
# Usage: bk-find-git-verify [DIR]
# Depends: GNU parallel 20210822, sort (GNU coreutils) 8.32
# Version: 0.0.1

# Define functions
yell() { echo "$0: $*" >&2; } # print script path and all args to stderr
die() { yell "$*"; exit 111; } # same as yell() but non-zero exit status
try() { "$@" || die "cannot $*"; } # runs args as command, reports args if command fails
git_verify_ops() {
    # usage: git_verify_ops arg1
    # input: arg1   git work tree root dir
    # output: none
    # depends: yell(), die(), try()
    local list_tags;
    
    # Check input
    ## End function early if arg1 not a dir
    if [[ ! $# -eq 1 ]]; then yell "ERROR:Incorrect number of args:$#"; return 1; fi;
    if [[ ! -d "$1" ]]; then yell "ERROR:Not a dir:$1"; return 1; fi;
    ## TODO: Check if "$1" is git repo
    yell "DEBUG:Running git_verify_ops on dir:$1";

    # Change work dir to target repo
    pushd "$1" 1>/dev/random 2>&1;

    # Get list of git tags
    list_tags="$(git tag --list)";
    
    # Verify git commit signatures
    yell "Starting git log of dir:$1";
    git log --show-signature 1>/dev/random 2>&1;
    yell "Ending git log of dir:$1";

    # Verify each tag
    while read -r tag; do
        yell "DEBUG:Verifying tag:$tag";
        git verify-tag "$tag" 1>/dev/random 2>&1;
    done < <(printf "%s" "$list_tags");

    # Return to original work dir
    popd 1>/dev/random 2>&1;

    # End function;
    return 0;
}; # Verify signatures on git commits and tags
main() {
    # depends: yell(), die(), try()
    # Check input
    if [[ ! $# -eq 1 ]]; then die "FATAL:Incorrect arg count:$#"; fi;
    if [[ ! -d "$1" ]]; then die "FATAL:Not a dir:$1"; fi;

    # Get list of dirs containing '.git' directory
    dir_list="$(find "$1" -type d -name ".git" 2>/dev/random | parallel dirname '{}' | sort -u)";

    # Perform git verify operations on each directory
    printf "%s" "$dir_list" | parallel git_verify_ops '{}';    
}; # main program

# Export functions
export -f yell die try git_verify_ops

# Run program
main "$@";