#!/bin/bash
###################################################################### 
#Copyright (C) 2023  Kris Occhipinti
#https://filmsbykris.com

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

#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 General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
###################################################################### 
dir="$HOME/mame/roms"
arg="$1"

function error(){
  echo "$*"
  exit 1
}

mkdir -p "$dir"
cd "$dir" || error "Can't Enter $dir"

function main(){
  search
  download_rom
  [[ "$arg" == "android" ]] && adb_push
}

#search game
function search(){
  url="https://gitlab.com/metalx1000/Mame-Arcade-ROM-List-By-Name/-/raw/master/rom.lst"
  rom="$(wget -qO- "$url"|fzf --prompt "Enter Game Title: "|cut -d\| -f2)"
  [[ $rom ]] || exit
}

#download rom
function download_rom(){
  url="https://archive.org/download/mame-merged/mame-merged/${rom}.zip"
  wget -c "$url"
}

function adb_push(){
  adb get-state || error "No Device Connected."
  adb push ${rom}.zip /sdcard/RetroArch/downloads/
  adb shell am force-stop com.retroarch
  adb shell am start -n com.retroarch/.browser.retroactivity.RetroActivityFuture -e ROM /sdcard/RetroArch/downloads/${rom}.zip -e LIBRETRO /data/data/com.retroarch/cores/mamearcade_libretro_android.so -e CONFIGFILE /storage/emulated/0/Android/data/com.retroarch/files/retroarch.cfg -e QUITFOCUS --activity-clear-task --activity-clear-top --activity-no-history
}

while [ 1 ]
do
  main
done
