#!/usr/bin/env bash

# exit on first failure
set -e

SED=$(which gsed || which sed)

ARGC=$#
while [[ $# > 1 ]]; do
  # Logic for returning nonzero based on answer here: https://stackoverflow.com/a/15966279/104648
  eval "${SED} -i '/^\([[:blank:]]*\)\(\/\/\)*\([[:blank:]]*\)\(#define\s\+\b${1}\b\).*$/{s//\1\3\4 ${2}/;h};\${x;/./{x;q0};x;q9}' Marlin/Configuration.h" ||
  eval "${SED} -i '/^\([[:blank:]]*\)\(\/\/\)*\([[:blank:]]*\)\(#define\s\+\b${1}\b\).*$/{s//\1\3\4 ${2}/;h};\${x;/./{x;q0};x;q9}' Marlin/Configuration_adv.h" ||
  eval "echo '#define ${1} ${2}' >>Marlin/Configuration.h" ||
  (echo "ERROR: opt_set Can't set or add ${1}" >&2 && exit 9)
  shift 2
done