#!/bin/bash

#playlist File
playlist="$HOME/.dmusic.m3u"

#wad dir
WADS="$HOME/.doom/"

#playlist Url
url='https://www.youtube.com/playlist?list=PLcUid3OP_4OVBK5JUVRshK25aIpuEWc-k'

#function
func="$1"

function main(){
  if [ "$func" = "update" ]
  then
    update
  elif [ "$func" = "maps" ]
  then
    deutex -wadi $WADS/*.wad|grep -i "^map"|awk '{print $1}'|sort
    echo "====================="
    echo -n "Number of MAPS: " 
    deutex -wadi $WADS/*.wad|grep -i "^map"|awk '{print $1}'|sort|wc -l
    exit
  elif [ "$func" = "music" ]
  then
    music 100
  else
    play
  fi
}

function update(){
  echo "Updating $playlist, please wait..."
  youtube-dl --get-id "$url" $cookie|\
    while read id;
    do 
      #echo "https://www.youtube.com/watch?v=$id";
      youtube-dl -g -f bestaudio $cookie "https://www.youtube.com/watch?v=$id";
    done > $playlist
  }

function music(){
  if [ "$#" -lt "1" ]
  then
    vol="50"
  else
    vol="$1"
  fi

  #tmux split "mpv --input-ipc-server=/tmp/mpvsocket --no-video --volume=$vol --shuffle \"$playlist\""
  tmux split "mpv --input-ipc-server=/tmp/mpvsocket --no-video --volume=$vol --shuffle $HOME/music/dmusic/* "
  #tmux split "mpv --input-ipc-server=/tmp/mpvsocket --no-video --volume=$vol --shuffle \"$url\""
}

function game(){
  wads="$(echo -n "-file ";find "$WADS" -iname "*.WAD"|while read wad;do echo "$wad";done |tr "\n" " ")"
  dehs="$(find "$WADS" -iname "*.deh"|while read deh;do echo "-deh $wdeh";done |tr "\n" " ")"
  echo "RUNNING: prboom-plus -nomusic $wads $deh"
  if [ "$func" = "doom1" ];
  then
    echo "==============Playing Doom 1================"
    prboom-plus -iwad /usr/share/games/doom/doom.wad -nomusic $wads $deh
  elif [ "$func" = "plutonia" ] || [ "$func" = "p" ];
  then
    echo "==============Playing Doom 1================"
    prboom-plus -iwad /usr/share/games/doom/plutonia.wad -nomusic
  elif [ "$func" = "tnt" ] || [ "$func" = "t" ];
  then
    echo "==============Playing Doom 1================"
    prboom-plus -iwad /usr/share/games/doom/tnt.wad -nomusic
  else
    prboom-plus -nomusic $wads $deh
  fi
}

function play(){
  music
  game
}

main 
echo "Goodbye"
