#!/bin/bash

BASE="timmytuffknuckles"
TOTAL=10
PARALLEL=3

DONE=0
FAILED=0

declare -a DONE_LIST=()

publish_one() {
  NAME="$1"

  echo "[START] $NAME"

  node -e "
    const fs = require('fs');
    const pkg = require('./package.json');
    pkg.name = '$NAME';
    fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
  "

  if npm publish --silent > /dev/null 2>&1; then
    echo "[DONE]  $NAME"
    DONE_LIST+=("$NAME")
    DONE=$((DONE + 1))
  else
    echo "[FAIL]  $NAME"
    FAILED=$((FAILED + 1))
  fi
}

draw_ui() {
  clear
  echo "=================================="
  echo "   NPM AUTO PUBLISH DASHBOARD"
  echo "=================================="
  echo ""
  echo "Progress: $DONE / $TOTAL"
  echo "Failed:   $FAILED"
  echo ""

  # progress bar
  PCT=$(( DONE * 100 / TOTAL ))
  BAR=$(( PCT / 5 ))

  printf "Progress: ["
  for ((i=0;i<20;i++)); do
    if [ $i -lt $BAR ]; then printf "█"; else printf " "; fi
  done
  printf "] %s%%\n\n" "$PCT"

  echo "Published packages:"
  for i in "${DONE_LIST[@]}"; do
    echo "  ✔ $i"
  done

  echo ""
  echo "Running..."
}

count=1

while [ $count -le $TOTAL ]
do

  while [ $(jobs -rp | wc -l | tr -d ' ') -ge $PARALLEL ]
  do
    draw_ui
    sleep 0.3
  done

  publish_one "${BASE}${count}" &

  count=$((count + 1))

  draw_ui

done

wait

draw_ui
echo ""
echo "ALL DONE"