#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

TOP=PDP_colorlight_top

rm -f ${TOP}.json ${TOP}.config ${TOP}.bit

yosys -p "synth_ecp5 -top ${TOP} -json ${TOP}.json" \
  PDP_colorlight_top.v \
  PDP_top.v \
  PDP_cpu.v \
  Datapath.v \
  Main_comps.v \
  "74 series.v" \
  Teletype.v \
  uart.v \
  brg.v \
  blk_ram16kx12.v \
  RAM.v \
  debounce.v

nextpnr-ecp5 --25k --package CABGA381 --speed 6 \
  --json ${TOP}.json \
  --lpf colorlight_i5.lpf \
  --textcfg ${TOP}.config \
  --timing-allow-fail \
  --freq 25

ecppack ${TOP}.config ${TOP}.bit

echo
echo "Build completed:"
echo "  ${TOP}.bit"
echo

if [ "$1" = "prog" ]; then
    echo "Programming FPGA..."
    ecpdap program ${TOP}.bit -f 5M
fi
