#!/bin/bash
# Load inventory and use it to look for missing symbols
# Author: Krisjanis Rijnieks
# Created: 2022-04-27

# TODO: Create whitelist (some parts from DigiKey are not electronics parts)

INVENTORY_URL="http://inventory.fabcloud.io/data/inv.json"
SOURCE="Digi-Key"

# Colored output
RED='\033[0;31m'
GREEN='\033[0;32m'
RESET='\033[0m'

# Error counting
ERRORS=0

echo "This script looks for parts that are not in the KiCad fab library yet. In order to add parts, make sure that the manufacturer number of the part is added to the keywords section of the library symbol."

# Read keywords from all KiCad fab library symbols
KEYWORD_LINES=$(cat ../fab.kicad_sym | grep --extended-regexp --only-matching -U 'property "ki_keywords" "([^"]*)"')
KEYWORDS=""
IFS=$'\n'
for LINE in ${KEYWORD_LINES}; do
   WORDS=$(echo ${LINE} | sed -En 's/property "ki_keywords" "([^"]*)"/\1/p')
   KEYWORDS="${KEYWORDS} ${WORDS}"
done

# Extract items matching source
# JQ is used here.
# RT*M: https://stedolan.github.io/jq/manual/
# Play: https://jqplay.org/
echo "Loading fab inventory..."
ITEMS=$(curl -s ${INVENTORY_URL} | jq -r '.topics[] | .sources."Digi-Key".categories[]? | .[] | .item')
echo "Looking for matches in the library..."
for ITEM in ${ITEMS}; do
  # TODO: Look for item in whitelist
  # Look for item in KiCad symbol library
  if [[ ${KEYWORDS} == *"${ITEM}"* ]]; then
    echo -e "${GREEN}${ITEM} found${RESET}"
  else
    echo -e "${RED}${ITEM} not found${RESET}"
    ERRORS=$(expr $ERRORS + 1)
  fi
done

echo "Total errors: ${ERRORS}"