#!/bin/sh
#set -x

firsttime() {
    cat << EOF

This script makes it easy to download tabs and work past the obfuscation
scheme used by tabsheaven.net.  (just go to www.tabsheaven.net and you'll 
understand)

This script needs the following tools:
* jot - print sequential or random data
* xurl - extracts urls from a file
* lynx - a general purpose distributed information browser for the
  World Wide Web

If you have these tools installed, comment out the prereq line from this script
EOF
    exit
}

# Comment out the following line once you've installed the prereq's
firsttime

if [ $# -lt 1 ]; then
    cat << EOF
Instructions:
- go to http://www.tabsheaven.net
- find the artist you like
- note the interpret id and number of tabs
- Run this script as such:

$0 artist id count

Or rename files in a directory:

$0 rename directory/*

EOF
    exit
fi

gpname() {
#	echo $1 | strings $j | sed 's/^[ 	]//g' | awk '/^FICH/ {getline b; print b}'| sed -e 's/[ 	\\()/"]/_/g'
	echo $1 | strings $j | sed 's/^[ 	]//g' | awk '/^FICH/ {getline b; print b}'| tr -cs '[:alnum:]' _
}


top=`pwd`
while [ $# -gt 0 ];
do
	case $1 in
	rename)
		shift
		for j in $*; do
			shift
			cd $top
			f=`gpname $j`
			dir=`dirname $j`
			j=`basename $j`
			mv $dir/$j $dir/"$f-$j"
		done
	;;
	*)
		cd $top
		if [ $? -gt 0 ]; then
			echo "cant cd to $dir" 
			exit 1
		fi
		pwd

		dir=$1
		id=$2
		mx=$3
		shift; shift; shift;

		ct=`echo "$mx / 20 + 1" | bc`

		echo getting $ct pages with $mx tabs for $dir
		if [ ! -d $dir ]; then
			mkdir $dir
		fi
		cd $dir
		if [ $? -gt 0 ]; then
			echo "Could not change to $dir"
			exit 1
		fi
		pwd

		for j in `jot $ct 0 $mx 20`
		do
		    lynx -dump "http://www.tabsheaven.net/interpret.php?id=$id&begin=$j"
		done | xurl | sort -u | grep free-guitar  | grep -v interpret | sed -e 's/^.*\///' > ${dir}-pages

		for j in `cat ${dir}-pages`
		do lynx -dump "http://www.tabsheaven.net/tab.php?id=$j"
		done | xurl | grep data > ${dir}-tabs

		wget -nd `cat ${dir}-tabs`
		mkdir old zip
		mv *.zip zip
		mv *.g* old
		for j in zip/*
		do
		  unzip $j
		done
		cd old

		for j in *
		do
			echo $j:
			f=`gpname $j`
			cp $j ../"$f-$j"
		done 2> ../${dir}-errors
	;;
	esac
done
