#!/bin/bash

# Input: file list in character encoding $enc with paths relative to $root
# Output: iriver playlist
# Examples of usage:
# Playlist for \Music\mozart:
#  find /home/user/music/mozart -type f -printf "mozart/%P\n" | sort | ./iriverpla.sh > mozart.pla
# Convert m3u playlist in character encoding ISO-8859-1 with paths relative to \Music
#  grep --after-context=1 '^#EXTINF:' input.m3u | grep --invert-match '^#EXTINF:' | ./iriverpla.sh ISO-8859-1 > output.pla

# References:
# http://iriverfile.sourceforge.net/iriver-playlist.html
# http://wiki.bath.ac.uk/display/~ma9mjo/iRiver+s10
# http://laszlopandy.com/2006/07/14/iriver-t10/
# http://www.pro-linux.de/files/iRiverPlaMaker3.py

# Tested with:
# iriver T30 firmware version 1.71 MTP
# GNU bash, Version 4.1.7(1)-release (x86_64-suse-linux-gnu)
# dirname (GNU coreutils) 7.1
# iconv (GNU libc) 2.11.2
# xxd V1.10 27oct98 by Juergen Weigert
# GNU sed Version 4.1.5
# Examples:
# GNU grep 2.5.4
# sort (GNU coreutils) 7.1
# find (GNU findutils) 4.4.2

# Author: Theo Wollenleben (alpha0x89 yahoo de)
# Date: 2010-12-29
# License: GPL

if [ -z "$1" ]; then
 enc="UTF-8"
else
 enc="$1"
fi
if [ -z "$2" ]; then
 root="\Music"
else
 root="$2"
fi
#heading="Quick List"

(while read name; do
 ((n++))
 dir="$(dirname "$name")"
 offset_hex=$(printf "%04x" $((${#root}+${#dir}+3)))
 name_hex=$(echo -n "$root"'\'"${name//\//\\}" | iconv -f "$enc" -t UNICODEBIG | xxd -p -l 510 -c 512)
 entry[$n]=$offset_hex$name_hex
done

head_hex=$(echo -n -e "iriver UMS PLA\0\0\0\0\0\0\0\0\0\0\0\0\0\0$heading" | xxd -p -l $((480-${#heading})) -c 512)
entry[0]=$(printf "%08x" $n)$head_hex

for ((k=0;k<=n;k++)); do
 e=${entry[$k]}
 echo -n $e
 printf "%0$((1024-${#e}))d"
done | xxd -p -r)
