#!/bin/sh
#mmc.sh - Launch the MMC-MIPS with a sh wrapper for ease and portability.
#Copyright 2018 by Prince Trippy programmer@verisimilitudes.net .

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU Affero General Public License version 3
#as published by the Free Software Foundation.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU Affero General Public License for more details.

#You should have received a copy of the GNU Affero General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
set -e
trap 'stty "${s:--g}" > /dev/null; rm -f "$i"' EXIT
name=$(echo "$0" | sed 's/.*\///')
case ${1:--h} in
    -v|--version) echo 'Meta-Machine Code targeted at MIPS for OpenBSD 6.3'; exit ;;
    -h|--help) echo "$name [[-h|--help][-v|--version] [save [data [metadata]]]]"; exit ;;
    *) i=$(mktemp '/tmp/mmc-in.XXXXXX')
       o=$(mktemp '/tmp/mmc-out.XXXXXX')
       if [ "$2" ]; then cat "$2"  > "$i"; fi
       truncate -s  20480 "$i"
       if [ "$3" ]; then cat "$3" >> "$i"; fi
       truncate -s 122880 "$i" ;;
esac; s=$(stty -g); stty raw -echo
cat "$i" - | mmc-mips-loader 2>| "$o" || true
clear; sync; w=$(wc -c < "$o"); n=$(($w-122880))
m="Unable to write output files; something is wrong; find raw file at $o."
if [ $w = 0 ]; then { echo 'No output desired.'; rm -f "$o"; exit; }; fi
if [ $((w%122880)) != 0 ]; then { echo "$m"; exit; }; fi
dd if="$o" of="$1.mips" skip="$n"          bs=1024 count=20  || { echo "$m"; exit; }
dd if="$o" of="$1.mmc"  skip=$(($n+20480)) bs=1024 count=100 || { echo "$m"; exit; }
rm -f "$o"