#!/usr/bin/env bash
set -euo pipefail

month="${1:-*}"

process_one() {
  inpath="$1"

  monthdir=$(printf "%s" "$inpath" \
    | grep -oE '/([^/]+-[^/]+)/' \
    | grep -oE '[^/]+')

  mkdir -p "$monthdir"

  out="$monthdir/$(basename -- "$inpath" .json).sqlite"
  if [[ -f "$out" ]]; then
    echo "$out exists, removing!"
    rm "$out"
  fi

  echo "$inpath --> $out"
  smogon-stats "$inpath" --output "$out"
}

export -f process_one

find ~/www.smogon.com/stats/$month/chaos -name '*.json' -print0 \
  | xargs --null -n1 -P12 bash -c 'process_one "$@"' _
