#!/usr/bin/env bash

set -e

input="${1:?input not set}"
source="${2:?variable source not set}"

css="$(cat "$input")"
IFS=$'\n'
for line in $css; do
    _match="$(grep -m 1 -oP '(?<=var\()[^)\s]+(?=\))' <<< "$line" || :)"
    if [[ ${_match:+x} == x ]]; then for match in $_match; do
        color="$(grep -m 1 -oP "(?<=$match: )[^;\s]+(?=;)(?:\s+)?" "$source" | tail -n1 || :)"
        if [[ ${color:+x} == x ]]; then
            echo "replacing var($match) with $color" 1>&2
            sed -i s/var\("$match"\)/"$color"/g "$input"
        else
            echo "$match not defined in $source" 1>&2
        fi
    done; fi
done