#!/bin/bash

banner="daPlay :: by shudder"

trap clear 0

play() {
  mpg123 -2q "$1" &> /dev/null &
  echo $! > ~/.daplay/pid
  continue
}

if ! (which dialog &> /dev/null); then
  echo "error: cannot find \`dialog'"
  exit 1
fi

if [ ! -f ~/.daplay/config ] || [ "$1" = "--config" ]; then
  rm -rf ~/.daplay
  mkdir ~/.daplay
  dialog --backtitle "$banner" --title "configure daPlay" --inputbox "enter your mp3 dir" 8 76 2> ~/.daplay/temp
  [ "$?" = "1" ] && exit 0
  dir="`cat ~/.daplay/temp`"
  [ ! $dir ] && exit 1
  echo "dir=\"$dir\"" > ~/.daplay/config
fi

. ~/.daplay/config
[ ! -d $dir ] && rm -fr ~/.daplay && $0

cd $dir &> /dev/null
dialog --backtitle "$banner" --infobox "loading tracks..." 3 40
(find -name \*.mp3 | sed "s/ /*/g;s/.mp3//g" | sort) > ~/.daplay/names 2> ~/.daplay/err

tracks=""
for i in `cat ~/.daplay/names` ; do
  tracks="$tracks `basename $i`"
done
echo $tracks | sed "s/ / mp3 /g" > ~/.daplay/playlist
tracks="`cat ~/.daplay/playlist` mp3"

while dialog --backtitle "$banner" --title "daPlay" --menu "choose track" 18 76 10 $tracks 2> ~/.daplay/lasttrack; do
     fullpath="`find -name $(cat ~/.daplay/lasttrack)* 2> /dev/null`"

  if ! (dd if=/dev/dsp of=/dev/null bs=1 count=1 &> /dev/null); then
         /bin/kill $(cat ~/.daplay/pid) &> /dev/null
         if [ "$?" != "0" ]; then
           if (command ps ax | grep mpg123 | grep -v grep) &> /dev/null; then
             dialog --title "daProblem" --yesno "the sound device is busy by mpg123.kill it and continue with your track?" 5 76
             [ "$?" = "0" ] && killall mpg123 && play $fullpath
           fi
           dialog --title "daProblem!" --msgbox "unable to open /dev/dsp!" 5 76
         else
           play $fullpath
         fi
  else
         play $fullpath
  fi


done

