#!/bin/bash
echo "Welcome to RVGL setup."

DIR="$(dirname "$(readlink -f "$0")")"

echo "WARNING: This will modify your RVGL installation in:"
echo -e "\t$DIR"
read -r -p "Are you sure? [y/N] " response
echo
if [[ ! "${response,,}" =~ ^(yes|y)$ ]]; then
  exit
fi

cd "$DIR"

echo "Fixing filenames..."
shopt -s globstar
re="^\./[^/]*\.dll$\|^\./lib/.*\.so.*$|^\./licenses/.*$"
for file in **; do
  dest="./${file,,}"
  file="${dest%/*}"/"${file##*/}"
  if [[ "$file" != "$dest" && ! "$file" =~ $re ]]; then
    [ ! -e "$dest" ] && mv -T "$file" "$dest" || echo "$file was not renamed"
  fi
done

echo "Clearing libs..."
rm -f ./lib/*.*

echo "Creating launcher..."
launcher="$HOME/.local/share/applications/RVGL.desktop"
mkdir -p "$HOME/.local/share/applications"
echo "[Desktop Entry]" > "$launcher"
echo "Comment=Re-Volt port for Linux" >> "$launcher"
echo "Terminal=false" >> "$launcher"
echo "Name=RVGL" >> "$launcher"
echo "Type=Application" >> "$launcher"
echo "Categories=Game;ArcadeGame;" >> "$launcher"
echo -n "Path=" >> "$launcher"
echo "$DIR" >> "$launcher"
echo -n "Exec=" >> "$launcher"
echo -n "$DIR" >> "$launcher"
echo "/rvgl" >> "$launcher"
echo -n "Icon=" >> "$launcher"
echo -n "$DIR" >> "$launcher"
echo "/icons/256x256/apps/rvgl.png" >> "$launcher"

echo "Setting permissions..."
chmod -R ugo+rw ./cache
chmod -R ugo+rw ./profiles
chmod -R ugo+rw ./replays
chmod -R ugo+rw ./times
chmod ugo+rw ./lib
chmod ugo+x ./rvgl
chmod ugo+x ./rvgl.32
chmod ugo+x ./rvgl.64
chmod ugo+x "$launcher"
chmod ugo+x ./alsoft_log
chmod ugo+x ./fix_cases

echo "Registering for lobby..."
./rvgl -register

echo "Done."
read -r -p "Press any key to continue." -n 1
echo
