#!/usr/bin/env bash
#
# fordir - run a command within each subdirectory
# usage: fordir [pwd]

# shellcheck shell=bash

ROOT="${PWD}"
PARALLEL=0
# EXPR='*/'
EXPR='.'
# default only top-level
MAXDEPTH_FLAG=${MAXDEPTH_FLAG:--d 1}
FDFIND_ARGS=""

# commandline args processing
POSITIONAL=()
while [ "$#" -gt 0 ]; do
  key="$1"
  case ${key} in
    -p | --parallel)
      PARALLEL=1
      shift # past value
      ;;
    -e | --expr | --expression) # only leaving this here for legacy reasons
      EXPR="$2"
      shift # past value
      shift # past value
      ;;
    -r | --recurse)
      MAXDEPTH_FLAG=
      shift
      ;;
    -f | --full-path) # apply regex to full path
      FDFIND_ARGS="${FDFIND_ARGS} --full-path"
      shift
      ;;
    -g | --glob) # apply regex to full path
      FDFIND_ARGS="${FDFIND_ARGS} --glob"
      shift
      ;;
    *)
      # save it in an array for later
      POSITIONAL+=("$1")
      # past argument
      shift
      ;;
  esac
done
# restore positional parameters
set -- "${POSITIONAL[@]}"

if [ "$#" -eq 1 ]; then
  ALLCMDS_RAW="$1"
else
  EXPR="$1"
  ALLCMDS_RAW="$2"
fi

# echo "${ALLCMDS_RAW}"

# shellcheck disable=SC2207,SC2086
DIRS=($(fd "${EXPR}" --type d ${MAXDEPTH_FLAG} ${FDFIND_ARGS}))

for DIR in "${DIRS[@]}"; do
  cd "${DIR}" || exit 1
  # shellcheck disable=SC2312
  allcmds=$(echo "${ALLCMDS_RAW}" \
    | sed "s|DIR|${DIR}|g" | sed "s|ROOT|${ROOT}|g")

  IFS=';' read -ra cmdarray <<EOF
${allcmds}
EOF
  for cmd in "${cmdarray[@]}"; do
    # echo $cmd
    if [ "${PARALLEL}" = 0 ]; then
      # echo "${cmd}"
      eval "${cmd}"
    else
      get="$(echo "${cmd}" | awk '{ print $1 }')"
      if [ "${get}" = "cd" ]; then
        eval "${cmd}"
      else
        # tmpfile="$(mktemp "$(basename "$0")".XXXXXX)"
        # eval nohup "$cmd" >"$tmpfile".log 2>&1 &
        eval nohup "${cmd}" >out.log 2>&1 &
      fi
    fi
  done
  cd "${ROOT}" || exit 1
done

wait
