#!/bin/bash

# Edit the first line with the path to your Beat Saber folder
beatsaberroot='/mnt/a/SteamLibrary/steamapps/common/Beat Saber'
# Leave this one be
customsongpath='Beat Saber_Data/CustomLevels'

# These characters are not allowed in filenames (per Windows)
# and I also removed spaces to make it friendlier to work with
# (this is also a cheat to pull the strings from json without quotes)
badchars='" ,\\\/\:\*\?<>\|'

# Folder name = 40 hexadecimal characters
# ${#foldername} -eq 40

# Not a perfect looping function as it'll loop over the permissions separately but it works
for line in `ls -l "${beatsaberroot}/${customsongpath}"`; do
 if [[ ${#line} -eq 40 ]]; then
  folder="$line"
  fulldir="${beatsaberroot}/${customsongpath}/${folder}"  

  # Some of my info.dat files are one big json string and my logic below dumps
  #  2.0.0_songName-2.0.0_songName-2.0.0_songName insead of the actual info...
  infolen=`wc -l "$fulldir/Info.dat" | cut -d' ' -f1`
  # Set our variables outside the if so they're usable at the end
  song='';artist='';mapper=''
  if [[ $infolen -gt 0 ]]; then
   # For the easy info.dat files just grab their information
   song=`grep _songName "$fulldir/Info.dat" | cut -d: -f2 | sed "s/[$badchars]//g"`
   artist=`grep _songAuthorName "$fulldir/Info.dat" | cut -d: -f2 | sed "s/[$badchars]//g"`
   mapper=`grep _levelAuthorName "$fulldir/Info.dat" | cut -d: -f2 | sed "s/[$badchars]//g"`

   #mv "${beatsaberroot}/${customsongpath}/${folder}" "$song-$artist-$mapper"
  else
   #tput setaf 1
   # -f2 = Song name
   # -f4 = Artist
   # -f5 = Mapper
   song=`cat "$fulldir/info.dat" | cut -d, -f2 | cut -d: -f2 | sed "s/[$badchars]//g"`
   artist=`cat "$fulldir/info.dat" | cut -d, -f4 | cut -d: -f2 | sed "s/[$badchars]//g"`
   mapper=`cat "$fulldir/info.dat" | cut -d, -f5 | cut -d: -f2 | sed "s/[$badchars]//g"`
  fi
  mv "$fulldir" "${beatsaberroot}/${customsongpath}/$song-$artist-$mapper" 2>/dev/null 
  [ $? -eq 0 ] && tput setaf 2 || tput setaf 1
  echo "${folder} is really $song-$artist-$mapper"
  tput sgr0
 fi
done
echo -e "\nRed means the folder could not be renamed (destination name already exists?) and green means everything should be good!"