#!/usr/bin/env bash

# put these on top of file

(set -o igncr) 2>/dev/null && set -o igncr; # cygwin encoding fix

# absolute path working directory
basecwd=${PWD}
# base script directory
basedir=`dirname "$0"`
# absolute path script directory
SCRIPT_DIR=$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd)
# get script path
SCRIPT=$(realpath "$0")
SCRIPTPATH=$(dirname "$SCRIPT")

# Detect Cygwin or MinGW
case "$(uname)" in
  *CYGWIN*)
    basedir=$(cygpath -w "$basedir")
    # make cygwin bin as priority
    export PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:$PATH"
    ;;
  *MINGW*)
    # make mingw bin as priority
    export PATH="/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:$PATH"
    ;;
esac

# parse and export .env file (dotenv)
if [ -f ".env" ]; then
  # Export the vars in .env into your shell:
  export $(egrep -v '^#' .env | xargs)
fi

node_modules=()
locks=()
yarn_caches=()

while IFS= read -r -d $'\0'; do
    locks+=("$REPLY")
done < <(find "${basecwd}" -name "yarn.lock" -print0)

unset IFS;

while IFS= read -r -d $'\0'; do
    locks+=("$REPLY")
done < <(find "${basecwd}" -name "package-lock.json" -print0)

unset IFS;

while IFS= read -r -d $'\0'; do
    node_modules+=("$REPLY")
done < <(find "${basecwd}" -name "node_modules" -print0)

unset IFS;

while IFS= read -r -d $'\0'; do
    yarn_caches+=("$REPLY")
done < <(find "${basecwd}" -wholename "*/.yarn/cache" -print0)

unset IFS;

#printf "%s\n" "${yarn_caches[@]}"
#printf "%s\n" "${node_modules[@]}"
#printf "%s\n" "${locks[@]}"

echo "removing locks"
for lock in "${locks[@]}"; do
    rm -rf "$lock" && echo "removed $lock" &
done

wait

paths=("${yarn_caches[@]}" "${node_modules[@]}")
#echo ${paths[@]}
#echo "count ${#paths[@]}"

# https://unix.stackexchange.com/questions/482393/bash-sort-array-according-to-length-of-elements

indexes=( $(
    for i in "${!paths[@]}" ; do
        printf '%s %s %s\n' $i "${#paths[i]}" "${paths[i]}"
    done | sort -nrk2,2 -rk3 | cut -f1 -d' '
))

sorted=()
for i in "${indexes[@]}" ; do
    sorted+=("${paths[i]}")
done

#printf "%s\n" "${sorted[@]}"

echo "removing node_modules and caches"

for file in "${sorted[@]}"; do
    rm -rf "$file" && echo "removed $file" &
done

wait

echo "cleaning tmp"

find . -name "tmp" -exec rm -rf '{}' +