#!/bin/bash -e
# 新しくダウンロードされたファイルを携帯プレーヤーに持ち出すスクリプト

get_flush_mountpoint()
{
ls -d * 2>/dev/null|while read -r i
do
if test -d "${i}"; then
if ! test -L "${i}"; then
if mountpoint "${i}">/dev/null; then
if mount|grep "${i}"|head -1|grep flush|grep -q vfat 2>/dev/null; then
echo "${i}"
return
else
continue
fi
fi
fi
fi
done
}

#MEDIAPATH=/media
MEDIAPATH=/media/disklessfun
cd "${MEDIAPATH}"|| exit 1

LABEL=$1

if test -n "${LABEL}"; then
DESTPATH=${LABEL}
else
DESTPATH=$(get_flush_mountpoint)
fi

if test -z "${DESTPATH}"; then
echo "DAP not connected"
exit 1
else
echo "${DESTPATH}"
fi

DESTPATH=${MEDIAPATH}/${DESTPATH}

if ! test -d "${DESTPATH}/MUSIC"; then
echo "MUSIC directory not found"
exit 1
fi

cd "${DESTPATH}" || exit 1

PATH=${PATH}:/usr/local/bin
DOCUMENTROOT=/home/disklessfun/Documents
FILELST="${DOCUMENTROOT}/Complete.lst"
DONELST="${DOCUMENTROOT}/Done.lst"
TMPDONELST="${DOCUMENTROOT}/tmp.Done.lst"
COMPLMSG="Copying complete, without errors."

test ! -e "${FILELST}" && echo "No files" && exit 0

#led-blink on
#led-red off
#led-orange off
#led-green off


EFLG=false
test -e "${DONELST}" && EFLG=true

while read i
do
if $EFLG; then
if (grep -q "$i"<"${DONELST}") then
continue
fi
fi
if test -e "${i}"; then
set -x
if test "${i##*\.}" == "wmv" || test "${i##*\.}" == "flv"; then
# WMVもしくはFLVはDAPには持ち出さないが、持ち出したことにする
echo "${i}" >> "${DONELST}"
set +x
continue
fi
cp -np "${i}" "${DESTPATH}/MUSIC"
if test $? -eq 0; then
echo "${i}" >> "${DONELST}"
fi
set +x
else
echo "${i} not found"
fi
done<"${FILELST}"


make-playlist.sh


#led-blink off
echo "${COMPLMSG}"

test ! -e "${DONELST}" && exit 0

# FILELSTに載っていないエントリーをDONELSTから削除する
grep -f "${FILELST}" "${DONELST}" > "${TMPDONELST}"
if ! (diff -u "${DONELST}" "${TMPDONELST}") then
set -x
mv "${TMPDONELST}" "${DONELST}"
set +x
else
rm "${TMPDONELST}"
fi
