#!/bin/bash

die () {
	echo "error: $@" >&2
	exit 128
}

PROMGEN="$1"
if [ -z "$PROMGEN" ]; then
	die "Missing PROMGEN"
fi

DIR="$2"
if [ -z "$DIR" ]; then
	die "Missing directory"
fi
DIR="$(realpath "$DIR")"

PROJECT="$3"
if [ -z "$PROJECT" ]; then
	die "Missing directory"
fi

FLASH_CHIP="$4"
if [ -z "$FLASH_CHIP" ]; then
	die "Missing FLASH_CHIP"
fi

shift 4

t=
trap "rm -rf -- \"\$t\"" EXIT
t="$(mktemp -d)" || die "can't create temp dir"

cp -- "$@" "$t"

cd "$t" || die "cd"

mkdir -p xilinx/projnav.tmp
mkdir -p xilinx/_ngo
mkdir -p "$DIR"/logs

if ! "${PROMGEN}" -w -p mcs -c FF -o ${PROJECT} -u 0 \
		${PROJECT}.bit -x "${FLASH_CHIP}" > "${PROJECT}.prom.log"; then
	cp -- "${PROJECT}".prom.log "$DIR"/logs
	cat ${PROJECT}.prom.log
	exit 128
fi

cp -- "${PROJECT}".prom.log "$DIR"/logs

[ -r "${PROJECT}".mcs ] || die "missing mcs file"
cp -- "${PROJECT}".mcs "$DIR"

exit 0
