#!/bin/sh
#  Description:
#    Script to copy and convert music to some directory. It was originally
#    created for DIVA MP3 Player, but can be usable for other things. It gets
#    all *.{ogg,mp3} files from source directory and converts them to mp3 in
#    destination directory on selected mountpoint (which will be mounted if it
#    is not).
#
#  License:
#    Copyright (C) 2002-2003 Michal Cihar
#
#    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
#
#  Requires:
#    cstocs realpath basename sh lame oggdec mp3info vorbiscomment
#
#  ChangeLog:
#    0.4 - better support for transfering whole directory tree
#        - ogg recompression support
#        - converting charset of title/artist/filename
#        - added cleanup on terminating
#        - added some colors :-)
#    0.3 - id3 tags support
#    0.2 - directories support
#    0.1 - initial version

################################################################################
# Configuration
MOUNTPOINT=/mnt/usb1
DEFAULT_LAMEOPTS="-m j -q 7 --vbr-new -V 6 -B 96"
SRC_CHARSET=il2
DST_CHARSET=ascii

################################################################################
# Script follows
if [ x$LAMEOPTS = x ] ; then
    LAMEOPTS="$DEFAULT_LAMEOPTS"
fi

echo "$(basename $0) version 0.4 by Michal Cihar <cihar at email dot cz>"

if [ "$#" -ne 2 ] ; then
    echo "Script to recompress mp3s and put them to $MOUNTPOINT"
    echo "usage: $(basename $0) srcdir dstdir"
    echo "   srcdir ... source directory"
    echo "   dstdir ... target directory (in $MOUNTPOINT)"
    echo "LAMEOPTS in environment can be used for specifying lame options"
    exit 100
fi

if grep -q "[[:space:]]${MOUNTPOINT}[[:space:]]" /proc/mounts ; then
    echo "\033[1;37m+ Mountpoint $MOUNTPOINT seems to be mounted\033[0m"
else 
    echo -en "\033[1;37m+ Attempting to mount $MOUNTPOINT ..."
    if mount "$MOUNTPOINT" ; then
        echo "succeeded\033[0m"
    else
        echo "\033[1;31mfailed\033[0m"
        exit 1
    fi
fi

DST=`echo "$2" | cstocs $SRC_CHARSET $DST_CHARSET`
if [ -d "$MOUNTPOINT/$DST" ] ; then
    echo "\033[1;37m+ Destination $MOUNTPOINT/$DST is directory, so it will be used"
else
    echo -n "\033[1;37m+ Destination $MOUNTPOINT/$DST is not directory, trying to create..."
    if mkdir -p "$MOUNTPOINT/$DST" ; then
        echo "succeeded\033[0m"
    else
        echo "\033[1;31mfailed\033[0m"
        exit 3
    fi
fi

SRC=`realpath "$1"`
if [ ! -d "$SRC" ] ; then
    echo "\033[1;31m+ Source $1 not found\033[0m"
    exit 4
fi

TMPFILE=`mktemp /tmp/to_diva.XXXXXXXXXX` || ( echo "Failed temp file creating!"; exit 2 )
rm -f "$TMPFILE"
TMPRAWFILE=`mktemp /tmp/to_diva.RAW.XXXXXXXXXX` || ( echo "Failed temp file creating!"; exit 2 )
rm -f "$TMPRAWFILE"
TMPLCKFILE=`mktemp /tmp/to_diva.LCK.XXXXXXXXXX` || ( echo "Failed temp file creating!"; exit 2 )
rm -f "$TMPLCKFILE"

cleanup() {
    echo -n "\033[1;37m+ Cleaning up temp..."
    for CYCLE in 1 2 ; do
        while [ x`cat "$TMPLCKFILE"$CYCLE` != x1 ]; do sleep 2;echo -n '.'; done
        rm -f "$TMPLCKFILE"$CYCLE
        rm -f "$TMPFILE"$CYCLE
        rm -f "$TMPRAWFILE"$CYCLE
    done
    echo "done\033[0m"
}
failure() {
    echo
    cleanup
    echo "\033[1;31m+ Transfer terminated\033[0m"
    exit
}
trap failure 1 2 15


echo "\033[1;37m+ Checking for needed subrectories"
find "$SRC" -type d | cut -b `echo "$SRC" | wc -c`- | grep -v '^$' | sed 's@^/@@' | sort | cstocs $SRC_CHARSET $DST_CHARSET | while read dirname ; do
    echo "\033[1;33m * Creating subdirectory \`$dirname'\033[0m"
    mkdir -p "$MOUNTPOINT/$1/$dirname"
done
echo "\033[1;37m+ All subdirectories should be ready\033[0m"


echo 1 > "$TMPLCKFILE"1
echo 1 > "$TMPLCKFILE"2
CYCLE=1
cd "$SRC"
echo "\033[1;37m+ Starting conversion"
find . -name '*.mp3' -o -name '*.ogg' | sed 's#^\./##' | sort | while read fname ; do
    echo "\033[1;33m * Converting \`$fname'\033[0m"
    if [ $CYCLE -eq 1 ] ; then
        CYCLE=2
    else
        CYCLE=1
    fi

    EXT=${fname##*.}
    DSTFILE=`echo ${fname%.$EXT} | cstocs $SRC_CHARSET $DST_CHARSET`.mp3

    if [ $EXT = ogg ] ; then
        TITLE=`vorbiscomment -l "$fname" | grep -i '^title=' | sed 's/^title=//i' | cstocs $SRC_CHARSET $DST_CHARSET`
        ARTIST=`vorbiscomment -l "$fname" | grep -i '^artist=' | sed 's/^artist=//i' | cstocs $SRC_CHARSET $DST_CHARSET`
    else
        # acquire id3 info
        ARTIST=`mp3info "$fname" -p "%a" | cstocs $SRC_CHARSET $DST_CHARSET`
        TITLE=`mp3info "$fname" -p "%t" | cstocs $SRC_CHARSET $DST_CHARSET`
    fi

    # wait for previous copying
    while [ x`cat "$TMPLCKFILE"$CYCLE` != x1 ]; do sleep 2;echo -n '.'; done

    # decompress ogg
    if [ $EXT = ogg ] ; then 
        oggdec -o "$TMPRAWFILE"$CYCLE "$fname"
        fname="$TMPRAWFILE"$CYCLE
    fi
    # recompress mp3
    if [ "$TITLE" ] ; then
        if [ "$ARTIST" ] ; then
            lame $LAMEOPTS --ta "$ARTIST" --tt "$TITLE" "$fname" "$TMPFILE"$CYCLE
        else
            lame $LAMEOPTS --tt "$TITLE" "$fname" "$TMPFILE"$CYCLE
        fi
    else 
        # empty title -> don't create tag
        lame $LAMEOPTS "$fname" "$TMPFILE"$CYCLE
    fi
    
    # wait for previously moved file
    while [ x`cat "$TMPLCKFILE"$CYCLE` != x1 ]; do sleep 2;echo -n '.'; done
    # move in background
    echo 0 > "$TMPLCKFILE"$CYCLE; 
    ( mv "$TMPFILE"$CYCLE "$MOUNTPOINT/$DST/$DSTFILE"; echo 1 > "$TMPLCKFILE"$CYCLE ) &
done

cleanup
echo "\033[1;32m+ Transfer done\033[0m"
