#!/bin/sh

set -e

if [ $# -eq 0 ]; then
    echo "Usage: $0 <regenerate|restore>"
    exit 1
fi

for dir in databases/ieee-*; do
    database=${dir#*-}
    (
        cd "$dir"
        if [ "$1" = "regenerate" ]; then
            if [ ! -f "/var/lib/ieee-data/${database}.csv" ]; then
                # known to happen for OUI-28 with ieee-data 20220827.1
                echo "Skipping database ${database} as a CSV for it doesn't exist."
		continue
            fi
            if [ ! -f "dbieee_${database}.h.orig" ]; then
                # keep a copy of the original "source" file
		# but only if we haven't done so already to make this idempotent
                mv "dbieee_${database}.h" "dbieee_${database}.h.orig"
            fi
            cp --preserve=timestamps "/var/lib/ieee-data/${database}.csv" .
            make create
        elif [ "$1" = "restore" ]; then
            if [ -f "dbieee_${database}.h.orig" ]; then
                mv "dbieee_${database}.h.orig" "dbieee_${database}.h"
            fi
            rm -f "${database}.csv"
        fi
    )
done
