#!/bin/sh

if [ $# == 0 ]; then
    ME=`basename "$0"`
    echo "Usage: $ME <M3U URL> [directory]"
    exit 1
fi

URL=$1
DIR='.'
if [ $# == 2 ]; then
    DIR=$2
fi

# check if it exists
STATUS=`curl -si $URL | head -1 | cut -d' ' -f2`
if [ "$STATUS" -ne "200" ]; then
    echo Failed to fetch ${URL}
    exit 1
fi

mkdir -p $DIR
if [ $? != 0 ]; then exit 1; fi
cd $DIR

# download
curl -s $URL | awk '!/^\#/' | sed "s/'/\\\'/" | xargs -t -n1 curl -O -C -
if [ $? != 0 ]; then
    cd ..
    exit 1;
fi

# fix names
perl -le 'for (@ARGV) { $was=$_; s/%(\d\d)/chr hex $1/eg; rename($was, $_) }' *

cd ..