#!/bin/bash

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

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

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

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

FPGA_CHIP="$4"
if [ -z "$FPGA_CHIP" ]; then
	die "Missing FPGA_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 ! "$PAR" -w -ol high -t 1 ${PROJECT}_map.ncd \
		${PROJECT}.ncd ${PROJECT}.pcf > "${PROJECT}.par.log"; then
	cp -- "${PROJECT}".par.log "$DIR"/logs
	cat ${PROJECT}.par.log
	exit 128
fi

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

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

exit 0
