#!/bin/sh
# Wrapper for kachikachi
# You can add extra command line arguments to all games at once
# using "cfg_nes_extra_args" variable in p0000_config
# or disable epilepsy protection using "cfg_disable_armet=y"

source /etc/preinit
script_init

filename="$(readlink -f "$1")"
dir=$(dirname $filename)
filebase="$(basename "$filename")"
extension="${filebase##*.}"
tmppath="$temppath/rom"
if [ "$extension" == "7z" ]; then
  rm -rf "$tmppath"
  mkdir -p "$tmppath"
  cd "$tmppath"
  tiny7zx x "$filename"
  filename="$(ls|head -n1)"
  mv "$filename" "rom.${filename##*.}"
  filename="$tmppath/rom.${filename##*.}"
fi
if [ "$extension" == "gz" ]; then
  rm -rf "$tmppath"
  mkdir -p "$tmppath"
  filebase="$(basename "$filebase" ".gz")"
  extension="${filebase##*.}"
  filename="$tmppath/rom.$extension"
  gunzip -c > "$filename"
fi
shift

args="$filename $@ $cfg_nes_extra_args"
[ "$cfg_disable_armet" == "y" ] && args="$(echo $args | sed 's/--enable-armet//g')"

while [ $# -gt 0 ]; do
  [ "$1" == "--load-state-file" ] && load=$2
  [ "$1" == "--replay-inputs" ] && playing_demo=1
  shift
done

if [ "$cfg_record_demo" == "y" ] && [ ! -z "$load" ] && [ -z "$playing_demo" ]; then
  mkdir -p $dir/autoplay
  demoid=$(basename $load)
  demoid=${demoid%.*}
  if touch "$dir/autoplay/$demoid.inputs.state"; then
    cp -f "$load" "$dir/autoplay/$demoid.inputs.state"
    args="$args --delete-previous-record --record-inputs $dir/autoplay/$demoid.inputs"
  fi
fi

[ -f "/bin/clover-kachikachi" ] && exec /bin/clover-kachikachi $args
[ -f "/usr/bin/clover-kachikachi" ] && exec /usr/bin/clover-kachikachi $args
