#/usr/bin/env sh

set -eo pipefail

if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <mapping.csv> <image.svg>"
    exit 1
fi

MAPPING_FILE=$1
IMAGE_FILE=$2

if [ ! -f "$MAPPING_FILE" ]; then
    echo "$MAPPING_FILE not found!"
    exit 1
fi

if [ ! -f "$IMAGE_FILE" ]; then
    echo "$IMAGE_FILE not found!"
    exit 1
fi

awk -F, '
NR==FNR {
    map[$1] = $2
    next
}
{
    line = $0
    for (key in map) {
        # Escape special characters in the key
        gsub_key = key
        gsub_key = gensub(/[$.*+?^{}|()[\]\\]/, "\\\\\\0", "g", gsub_key)
        gsub(gsub_key, map[key], line)
    }
    print line
}' $MAPPING_FILE $IMAGE_FILE
