set -euo pipefail
YS=../../yosys

mkdir -p temp

# non-POSIX sed -i inconsistency workaround
remove_empty_lines() {
    local file="$1"
    sed '/^$/d' "$file" > temp/tmp
    mv temp/tmp "$file"
}

# write_rtlil and dump are equivalent
$YS -p "read_verilog -sv everything.v; copy alu zzz; proc zzz; dump -o temp/roundtrip-text.dump.il; write_rtlil temp/roundtrip-text.write.il"
remove_empty_lines temp/roundtrip-text.dump.il
remove_empty_lines temp/roundtrip-text.write.il
# Trim first line ("Generated by Yosys ...")
tail -n +2 temp/roundtrip-text.write.il > temp/roundtrip-text.write-nogen.il
diff temp/roundtrip-text.dump.il temp/roundtrip-text.write-nogen.il

# Loading and writing it out again doesn't change the RTLIL
$YS -p "read_rtlil temp/roundtrip-text.dump.il; write_rtlil temp/roundtrip-text.reload.il"
remove_empty_lines temp/roundtrip-text.reload.il
tail -n +2 temp/roundtrip-text.reload.il > temp/roundtrip-text.reload-nogen.il
diff temp/roundtrip-text.dump.il temp/roundtrip-text.reload-nogen.il

# Hashing differences don't change the RTLIL
$YS --hash-seed=2345678 -p "read_rtlil temp/roundtrip-text.dump.il; write_rtlil temp/roundtrip-text.reload-hash.il"
remove_empty_lines temp/roundtrip-text.reload-hash.il
tail -n +2 temp/roundtrip-text.reload-hash.il > temp/roundtrip-text.reload-hash-nogen.il
diff temp/roundtrip-text.dump.il temp/roundtrip-text.reload-hash-nogen.il
