#!/usr/bin/env bash

IFS='/' read -r -a PINPATH <<< "$1"
DIR=${PINPATH[0]}
NAM=${PINPATH[1]}

SED=$(which gsed sed | head -n1)

shift
while [[ $# > 1 ]]; do
  PIN=$1 ; VAL=$2
  FOUT="${DIR}/pins_${NAM}.h"
  eval "${SED} -i '/^[[:blank:]]*\(\/\/\)*[[:blank:]]*\(#define \+${PIN}\b\).*$/{s//\2 ${VAL}/;h};\${x;/./{x;q0};x;q9}' Marlin/src/pins/${FOUT}" ||
  (echo "ERROR: pins_set Can't find ${PIN} in ${FOUT}" >&2 && exit 9)
  shift 2
done
