#!/usr/bin/env bash
# FSCK subfolders git projects.
#
# Actions taken: git fsck --no-dangling --full
#
# Copyright 2023 Ismo Vuorinen. All Rights Reserved.
# License: MIT <https://opensource.org/license/mit/>

set -euo pipefail

# Enable verbosity with VERBOSE=1
VERBOSE="${VERBOSE:-0}"

# Function to print messages if VERBOSE is enabled
# $1 - message (string)
msg()
{
  [ "$VERBOSE" -eq 1 ] && echo "$1"
}

# Function to perform git fsck on a repository
# $1 - directory (string)
fsck_repo()
{
  local dir=$1
  msg "Processing dir: $dir"
  (
    cd "$dir" || exit 1
    if [ -d ".git" ]; then
      git fsck --no-dangling --full --no-progress
      echo ""
    fi
  )
}

# Main function
main()
{
  local starting_path=${1:-$(pwd)}
  local dirs
  dirs=$(find "$starting_path" -mindepth 1 -maxdepth 1 -type d)

  for dir in $dirs; do
    fsck_repo "$dir"
  done

  echo ""
  echo "Done."
}

main "$@"
