#!/bin/sh

# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# Version 1.2
# Enter 1, 2 or 3 tags. Tag is just part of file name and path for music you 
# want to listen separated by space. To configure, edit the script.
# Order of tags is IMPORTANT, but non case-sensitive.
#
# Usage: playthis.sh [options] tag1 tag2 tag3
#
#          -shuffle        Shuffle mode
#          -a              Play all music in $PLAYTHISLIST in shuffle mode
#          --index         Search for music to create playlist
#          --copy          Copy music to $COPYDIR
#          --help          Prints this message
#
# Examples:
# % playthis.sh rolling stones satisfaction
# % playthis.sh -shuffle primal scream
#
# Variables:
# $PLAYTHISLOC1|2         Music locations. (default: $HOME/music1, $HOME/music2)
#                         BE CAREFUL: if you have spaces in music locations, in-
#                         stance them with "?" (without quotes); if you don't 
#                         need second music location, leave NONE.
#
# $PLAYTHISDB             Where to store database. (default: $HOME/.playthisdb)
#
# $COPYDIR                Where to store copied files. (default: .)
#
# $PLAYER                 Your player. Expected values are "mplayer" and "mpd".

PLAYTHISCONF=~/.playthis

PLAYER=mplayer

PLAYTHISLOC1=/media/windows/profiles/home/almarkov/music/
PLAYTHISLOC2=/media/windows/profiles/home/xenial/My?Music/
PLAYTHISDB=/data/media/music/playlist
PLAYTHISMPDDB=/data/media/music/plaympdlist #check pressence

COPYDIR=$PLAYTHISCONF/filldir/

FILLDIR=$PLAYTHISCONF/filldir/
FILLLIM=1000
INDENT=5 


## Checking for config directory

if [ -e $PLAYTHISCONF ] && [ -d $PLAYTHISCONF ]
    then
    true
else
    mkdir $PLAYTHISCONF
    echo -e "\vConfig directory succesfully created"
    exit 0
fi

if [ $# -eq 0 ]
    then
    echo -e "\vYou must give/supply at least one tag and/or option."
    echo -e "\vUsage: playthis.sh [options] tag1 tag2 tag3"
    echo -e "For more information use --help\v"
    exit 1
fi

## --help

if [ $# -eq 1 ] && [ $1 = --help ]
    then
    echo -e "\vEnter 1, 2 or 3 tags. Tag is just part of filename and path for music you want \nto listen separated by space. To configure, edit the script."
    echo -e "\vUsage: playthis.sh [options] tag1 tag2 tag3"
    echo -e "\v\t -shuffle\t Shuffle mode"
    echo -e "\t -a\t\t Play all music in \$PLAYTHISDB in shuffle mode"
    echo -e "\t --index\t\t Search for music to create playlist"
    echo -e "\t --copy\t\t Copy music to $COPYDIR"
    echo -e "\t --help\t\t Prints this message"
    echo -e "\vExamples:"
    echo -e "% playthis.sh stones satisfaction"
    echo -e "% playthis.sh -shuffle primal scream"
    echo -e "\vVariables:"
    echo -e "\$PLAYTHISLOC1|2 \tMusic locations. (default: \$HOME/music1, \$HOME/music2)" 
    echo -e "\t\t\tBE CAREFUL: if you have spaces in music locations, in-\n\t\t\tstance them with \"?\" (without quotes); if you don't ne\n\t\t\ted second music location, leave NONE."
    echo -e "\$PLAYTHISDB \t\tWhere to store playlist. (default: \$HOME/.playthislist)\v"
    exit 1
fi

## Creating playlist

if [ $# -eq 1 ] && [ $1 = --index ] && [ $PLAYTHISLOC1 = NONE ] && [ $PLAYTHISLOC2 = NONE ]
    then
    echo "You must specify at least one music location"
    exit 1
fi

if [ $# -eq 1 ] && [ $1 = --index ] && [ $PLAYTHISLOC1 != NONE ] && [ $PLAYTHISLOC2 = NONE ]
    then
    find $PLAYTHISLOC1 -name "*[m4a, mp3, wma]" > $PLAYTHISDB
    echo "Playlist created ($PLAYTHISDB)"
    exit 0
fi

if [ $# -eq 1 ] && [ $1 = --index ] && [ $PLAYTHISLOC1 = NONE ] && [ $PLAYTHISLOC2 != NONE ]
    then
    find $PLAYTHISLOC2 -name "*[m4a, mp3, wma]" > $PLAYTHISDB
    echo "Playlist created ($PLAYTHISDB)"
    exit 0
fi

if [ $# -eq 1 ] && [ $1 = --index ] && [ $PLAYTHISLOC1 != NONE ] && [ $PLAYTHISLOC2 != NONE ]
    then
    find $PLAYTHISLOC1 -name "*[m4a, mp3, wma]" > $PLAYTHISDB && find $PLAYTHISLOC2 -name "*[m4a, mp3, wma]" >> $PLAYTHISDB
    echo "Playlist created ($PLAYTHISDB)," `sed -n '$=' $PLAYTHISDB` songs
    exit 0
fi

## --copy

if [ $# -eq 2 ] && [ $1 = --copy ]
    then
    grep -i $2 $PLAYTHISDB | while read line
       do
       cp -ufv "$line" $COPYDIR
     done
    chmod 0644 $COPYDIR/*
    exit 0
fi

if [ $# -eq 3 ] && [ $1 = --copy ]
    then
    grep -i $2 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
    grep -i $3 /tmp/playthislist.1.tmp | while read line
       do
       cp -ufv "$line" $COPYDIR
     done
    chmod 0644 $COPYDIR/*
    exit 0
fi

if [ $# -eq 4 ] && [ $1 = --copy ]
    then
    grep -i $2 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
    grep -i $3 /tmp/playthislist.1.tmp >> /tmp/playthislist.2.tmp &&
    grep -i $4 /tmp/playthislist.2.tmp | while read line
       do
       cp -ufv "$line" $COPYDIR
     done
    chmod 0644 $COPYDIR/*
    exit 0
fi

## --fill and --autofill related variables
# Checking if $FILLDIR exist. If not, create it
if [ -e $FILLDIR ] && [ -d $FILLDIR ]
    then
    true
else
    mkdir $FILLDIR
fi

# Checking $INDENT value, if empty, using 5Mb (5120 kilobytes)
if [ -z $INDENT ]
    then
    echo "Indent value is empty, 5Mb will be used"
    $indentKilobyte=5120
else
    indentKilobyte=$(($INDENT*1024))
fi

# Checking $FILLLIM value, if empty asking for it
if  [ -z $FILLLIM ]
    then
    echo -n -e "\vEnter fill limit for this tag(s) (Mb): "
    read FILLLIM
    fillLimKilobyte=$(($FILLLIM*1024-5120))
    echo "Will be used $fillLimKilobyte kilobytes for tag \"$2\""
else
    fillLimKilobyte=$(($FILLLIM*1024-5120))
    echo "Will be used $fillLimKilobyte kilobytes for tag \"$2\""
fi

## --fill
if [ $# -eq 2 ] && [ $1 = --fill ]
    then
    FILLED=0
    grep -i $2 $PLAYTHISDB | while [ $FILLED -lt $fillLimKilobyte ] && read line
      do	
      cp -ufv "$line" $FILLDIR && FILLED=("`du $FILLDIR | sed -e 's/\/.*//'`")
      chmod 0644 $FILLDIR/*
    done
    exit 0
fi

## --interactive

# if [ $# -eq 1 ] && [ $1 = --interactive ]
#     then
#     FILLED=0
#     echo -e "\vPlease, specify size (Mb) of selection and up to three tags (order is important)" #rephrase later
#     echo -e "Example: 20 artist album song (using 20Mb for tags \"artist\", \"album\" and \"song\")\v"
#     read i1size i1tag1 i1tag2 i1tag3
#     i1sizeKilobyte=$(($i1size*1024))
#     echo -e "You entered \""$i1tag1"\" \""$i1tag2"\" \""$i1tag3"\" and "$i1size"Mb ("$i1sizeKilobyte"Kb) for them"
#     exit 0
# fi

## --autofill

# plain autofill
if [ $# -eq 1 ] && [ $1 = --autofill ]
    then
    FILLED=0
    RANGE=`sed -n '$=' $PLAYTHISDB`
    echo $RANGE
      
    while [ $FILLED -lt $fillLimKilobyte ]
      do

      lineNumRand=$RANDOM
      let "lineNumRand %= $RANGE"
      lineNumNorm=$lineNumRand

      if [ $lineNumNorm -eq 0 ]
	  then
	  lineNumNorm=$(($lineNumRand+1))
      else
	  lineNumNorm=$lineNumRand
      fi

      cp -ufv "`sed ''"$lineNumNorm"'q;d' $PLAYTHISDB`" $FILLDIR && FILLED=("`du $FILLDIR | sed -e 's/\/.*//'`")

    done
    
    chmod 0644 $FILLDIR/*
    rm /tmp/playthislist.*.tmp
    exit 0
fi

# 1 tag was specified
if [ $# -eq 2 ] && [ $1 = --autofill ]
    then
    FILLED=0

    grep -i $2 $PLAYTHISDB > /tmp/playthislist.1.tmp
    RANGE=`sed -n '$=' /tmp/playthislist.1.tmp`
      
    while [ $FILLED -lt $fillLimKilobyte ]
      do

      lineNumRand=$RANDOM
      let "lineNumRand %= $RANGE"
      lineNumNorm=$lineNumRand

      if [ $lineNumNorm -eq 0 ]
	  then
	  lineNumNorm=$(($lineNumRand+1))
      else
	  lineNumNorm=$lineNumRand
      fi

      cp -ufv "`sed ''"$lineNumNorm"'q;d' /tmp/playthislist.1.tmp`" $FILLDIR && FILLED=("`du $FILLDIR | sed -e 's/\/.*//'`")
      
    done

    chmod 0644 $FILLDIR/*
    rm /tmp/playthislist.*.tmp    
    exit 0
fi

# 2 tags was specified
if [ $# -eq 3 ] && [ $1 = --autofill ]
    then
    FILLED=0

    grep -i $2 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
    grep -i $3 /tmp/playthislist.1.tmp >> /tmp/playthislist.2.tmp &&    

    RANGE=`sed -n '$=' /tmp/playthislist.2.tmp`
      
    while [ $FILLED -lt $fillLimKilobyte ]
      do

      lineNumRand=$RANDOM
      let "lineNumRand %= $RANGE"
      lineNumNorm=$lineNumRand

      if [ $lineNumNorm -eq 0 ]
	  then
	  lineNumNorm=$(($lineNumRand+1))
      else
	  lineNumNorm=$lineNumRand
      fi

      cp -ufv "`sed ''"$lineNumNorm"'q;d' /tmp/playthislist.2.tmp`" $FILLDIR && FILLED=("`du $FILLDIR | sed -e 's/\/.*//'`")

    done

    chmod 0644 $FILLDIR/*
    rm /tmp/playthislist.*.tmp
    exit 0
fi

# 3 tags was specified
if [ $# -eq 4 ] && [ $1 = --autofill ]
    then
    FILLED=0

    grep -i $2 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
    grep -i $3 /tmp/playthislist.1.tmp >> /tmp/playthislist.2.tmp &&
    grep -i $4 /tmp/playthislist.2.tmp >> /tmp/playthislist.3.tmp &&

    RANGE=`sed -n '$=' /tmp/playthislist.3.tmp`
      
    while [ $FILLED -lt $fillLimKilobyte ]
      do

      lineNumRand=$RANDOM
      let "lineNumRand %= $RANGE"
      lineNumNorm=$lineNumRand

      if [ $lineNumNorm -eq 0 ]
	  then
	  lineNumNorm=$(($lineNumRand+1))
      else
	  lineNumNorm=$lineNumRand
      fi

      cp -ufv "`sed ''"$lineNumNorm"'q;d' /tmp/playthislist.3.tmp`" $FILLDIR && FILLED=("`du $FILLDIR | sed -e 's/\/.*//'`")

    done

    chmod 0644 $FILLDIR/*
    rm /tmp/playthislist.*.tmp
    exit 0
fi

## Defining player ($PLAYER)

if [ $PLAYER != "mplayer" ] && [ $PLAYER != "mpd" ]
    then
    echo -e "\vCheck $PLAYER value. Expected 'mplayer' or 'mpd'."
    exit 1
fi

## MPlayer defined, checking for -a and -shuffle option

if [ $PLAYER == "mplayer" ]
    then

    if [ $# -eq 1 ] && [ $1 = -a ]
	then
	mplayer -shuffle -playlist $PLAYTHISDB
	exit 0
    fi
    
    if [ $# -eq 2 ] && [ $1 = -shuffle ]
	then
	grep -i $2 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
	mplayer -shuffle -playlist /tmp/playthislist.1.tmp && rm /tmp/playthislist.*.tmp
	exit 0
    fi
    if [ $# -eq 1 ] && [ $1 != -shuffle ]
	then
	grep -i $1 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
	mplayer -playlist /tmp/playthislist.1.tmp && rm /tmp/playthislist.*.tmp
	exit 0
    fi
    
    if [ $# -eq 3 ] && [ $1 = -shuffle ]
	then
	grep -i $2 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
	grep -i $3 /tmp/playthislist.1.tmp >> /tmp/playthislist.2.tmp &&
	mplayer -shuffle -playlist /tmp/playthislist.2.tmp && rm /tmp/playthislist.*.tmp
	exit 0
    fi
    if [ $# -eq 2 ] && [ $1 != -shuffle ]
	then
	grep -i $1 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
	grep -i $2 /tmp/playthislist.1.tmp >> /tmp/playthislist.2.tmp &&
	mplayer -playlist /tmp/playthislist.2.tmp && rm /tmp/playthislist.*.tmp
	exit 0
    fi
    
    if [ $# -eq 4 ] && [ $1 = -shuffle ]
	then
	grep -i $2 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
	grep -i $3 /tmp/playthislist.1.tmp >> /tmp/playthislist.2.tmp &&
	grep -i $4 /tmp/playthislist.2.tmp >> /tmp/playthislist.3.tmp &&
	mplayer -shuffle -playlist /tmp/playthislist.3.tmp && rm /tmp/playthislist.*.tmp
	exit 0
    fi
    if [ $# -eq 3 ] && [ $1 != -shuffle ]
	then
	grep -i $1 $PLAYTHISDB > /tmp/playthislist.1.tmp &&
	grep -i $2 /tmp/playthislist.1.tmp >> /tmp/playthislist.2.tmp &&
	grep -i $3 /tmp/playthislist.2.tmp >> /tmp/playthislist.3.tmp &&
	mplayer -playlist /tmp/playthislist.3.tmp && rm /tmp/playthislist.*.tmp
	exit 0
    fi
    exit 0
fi

## MPD defined, checking for -a and -shuffle option

if [ $PLAYER == "mpd" ]
    then
    echo -e "\v--- MPD is NOT completely defined yet. ---\v"
    #checking symlinks for mpd

    PLAYTHISLINKS=$PLAYTHISCONF/playthislinks
    if [ -e $PLAYTHISLINKS ] && [ -d $PLAYTHISLINKS ]
	then
	true
    else
	mkdir $PLAYTHISLINKS
    fi

    PLAYTHISLINKS_array="$PLAYTHISLINKS/playthisloc1 $PLAYTHISLINKS/playthisloc2"
    for muslink in $PLAYTHISLINKS_array
      do
      if [ -e $muslink ] && [ -h $muslink ]
	  then
	  true
      else
	  ln -s $PLAYTHISLOC1 $PLAYTHISLINKS/playthisloc1
	  ln -s $PLAYTHISLOC2 $PLAYTHISLINKS/playthisloc2
      fi
    done
    
    #check mpd config
    if [ -f ~/.mpdconf ]
	then
	echo -e "---.mpdconf exists, ok---"
	oldMPD_MusicDirectory=`grep -i music_directory ~/.mpdconf | sed -e 's/music_directory[ \t]*"//;s/"$//' | sed "s|~|$HOME|g"`
	MPD_db=`grep -i db_file ~/.mpdconf | sed -e 's/db_file[ \t]*"//;s/"$//' | sed "s|~|$HOME|g"`

	if [ $oldMPD_MusicDirectory != $PLAYTHISLINKS ]
	    then
	    echo -e "\vCheck Your MPD config (~/.mpdconf): "
	    echo -e "You should have \"music_directory\" point exactly to \$PLAYTHISCONF/playthislinks"
	    echo -e "\vMPD music directory:\t\t$oldMPD_MusicDirectory"
	    echo -e "playthis.sh symlinks directory:\t$PLAYTHISLINKS"
	    echo -e "\vRepair manualy."
	    exit 1
	fi
	
	if [ -f $MPD_db ]
	    then
	    echo mpd db exist
	else
	    echo -e "\vYou don't have MDP DB file yet."
	    echo -e "You have 5 seconds to press Ctrl-c and do it manually with 'mpd --create-db'."
	    sleep 5s && mpd --create-db;
	fi
    else
	echo -e "Your MPD config (~/.mpdconf) missing. Repair manualy"
	exit 1
    fi

    if [ $# -eq 1 ]
	then
	mpd && mpc clear
	mpc listall > $PLAYTHISMPDDB
	grep -i $1 $PLAYTHISMPDDB | mpc add && mpc play
	exit 0
    fi

fi

