#!/bin/bash
#pMusic
#Copyright 2008,2009,2010,2011,2012,2013,2014
#Sigmund Berglund

cat $WORKDIR/playlist | awk -F '|' '{print "|" $2 "|" $3 "|" $4 "|" $5}' > $WORKDIR/playlist1
IFS=$'\n'
. $HOME/.pmusic/pmusicrc
export WORKDIR="$HOME/.pmusic/tmp"
[ ! -d "$STORAGE_DIR/storage_playlist/" ] && mkdir "$STORAGE_DIR/storage_playlist/"
DATO="`date +%Y\_%m\_%d\_\(%H:%M:%S\)`"

#check if list is not empty
if [ -s $WORKDIR/playlist ]; then
	ls -1 "$STORAGE_DIR/storage_playlist/" > $WORKDIR/tmp
	while read I; do
		[ ! "`diff "$STORAGE_DIR/storage_playlist/$I" $WORKDIR/playlist1`" ] && exit
	done < $WORKDIR/tmp
	#---
	cp $WORKDIR/playlist1 "$STORAGE_DIR/storage_playlist/Playlist_$DATO"
	echo "Playlist_""$DATO" > $WORKDIR/PLAYLIST_NAME
	#keep only the 30 newest in storage
	ls -1 "$STORAGE_DIR/storage_playlist/" | tail -n 30 > $WORKDIR/tmp_ls
	ls -1 "$STORAGE_DIR/storage_playlist/" > $WORKDIR/tmp_ls2
	while read I; do
		[ ! "`grep -F "$I" $WORKDIR/tmp_ls`" ] && rm "$STORAGE_DIR/storage_playlist/$I"
	done < $WORKDIR/tmp_ls2
fi
exit 0