#!/bin/bash

if [[ "$1" == "" ]] ; then
  if [[ ! -d /opt/pitrex/roms/vectrex ]] ; then
    echo vecx: directory /opt/pitrex/roms/vectrex does not exist. \(current directory: `pwd`\)
    exit 0
  fi
else
  if [[ ! -f /opt/pitrex/roms/vectrex/$1.BIN ]] ; then
    echo vecx: file /opt/pitrex/roms/vectrex/$1.BIN does not exist. \(current directory: `pwd`\)
    exit 0
  fi
fi
    
trap ctrl_c INT

function ctrl_c() {
    echo "** Trapped CTRL-C"
    # state 0xa [HDMI CEA (16) RGB lim 16:9], 1920x1080 @ 60.00Hz, progressive
    #/boot/config.txt:
    # #hdmi_safe=1
    # # uncomment if hdmi display is not detected and composite is being output
    # hdmi_force_hotplug=1
    # hdmi_group=1
    # hdmi_mode=16
    # #hdmi_drive=2
    # #config_hdmi_boost=4
    sudo tvservice -p
    sudo chvt 2                      # change to different virtual terminal
    sudo chvt 1                      # change back to the previous virtual terminal
    # need to do this automatically from saved tvservice output:
    fbset -g 1920 1080 1920 1080 32  # adjust the size of the framebuffer
    echo -n ondemand | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor > /dev/null
}

if [[ "$1" == "" ]] ; then
    echo -n performance | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor > /dev/null
    sudo tvservice --off
    # Minestorm.  Would be nice if vecx could put up a menu as in vecx.direct
    sudo ./vecx
elif [ -f /opt/pitrex/roms/vectrex/$1.BIN ] ; then
    echo -n performance | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor > /dev/null
    sudo tvservice --off
    sudo ./vecx /opt/pitrex/roms/vectrex/$1.BIN
elif [ -f /opt/pitrex/vectrex/$1.BIN ] ; then
    # deprecated location
    echo -n performance | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor > /dev/null
    sudo tvservice --off
    sudo ./vecx /opt/pitrex/vectrex/$1.BIN
elif [ -f ./roms/$1.BIN ] ; then
    # very deprecated location
    echo -n performance | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor > /dev/null
    sudo tvservice --off
    sudo ./vecx `pwd`/roms/$1.BIN
else
    echo "vecx: cannot find rom $1.BIN"
    echo "Please put the Vectrex roms ( upper case filenames ) in /opt/pitrex/roms/vectrex/"
    exit 1
fi

sudo tvservice -p
sudo chvt 2                      # change to different virtual terminal
sudo chvt 1                      # change back to the previous virtual terminal
# need to do this automatically from saved tvservice output:
fbset -g 1920 1080 1920 1080 32  # adjust the size of the framebuffer
echo -n ondemand | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor > /dev/null
