#!/bin/bash
#***************************************************************************
#*             __________               __   ___.
#*   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
#*   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
#*   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
#*   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
#*                     \/            \/     \/    \/            \/
#* File: rockbox_downloader.sh
#* Version: 0.8.1 - 05-13-2007 - Initial Public Release
#* Description: Script to automatically download and extract rockbox to my mp3
#* player (If mp3 player doesn't have latest build already).
#* My hope is to integrate this into a UDEV script so that it will automatically
#* run when I plug my mp3 player into my computer. I have tested this with my
#* Archos Jukebox Recorder. It should work with all rockbox supported players.
#* This script will not install a rockbox bootloader. it will just extract the
#* latest firmware to the mp3 player.
#* 
#* TODO: Add a --force option.
#* TODO: Figure out how to integrate this with udev.
#* TODO: Automatically Determine where mp3 player is mounted.
#* 
#* Copyright (C) 2007 Menachem Shapiro
#*
#* This script is subject to the GNU General Public License.
#*
#* This script is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
#* KIND, either express or implied.
#*
#****************************************************************************/

###################################
###################################
# Variables for user to edit:
###################################
###################################

# $MODEL will be determined later if 'rockbox-info.txt' exists on player. So, if
# your player has Rockbox firmware later than April 22, 2007 you can ignore
# this variable. If not, please edit $MODEL to reflect your player
# (check http://download.rockbox.org/daily/ for proper name to use)
# [e.g. The iRiver H320 would be MODEL=h300] - It is case sensitive
MODEL=recorder 

# Edit $PATHTOPLAYER to reflect your mp3 player's mount point.
# If you want to test out the script, comment out $PATHTOPLAYER. The script will
# then create a subfolder in the current directory, and put the files there.
PATHTOPLAYER=/media/JUKEBOX

###################################
###################################
# END Variables for user to edit
###################################
###################################

###################################
# Dependency Checking
###################################
DEPSNEEDED=
for i in wget lynx 
do
	which $i >/dev/null
	if [[ $? -ne 0 ]];then #dependency $i is needed
		DEPSNEEDED="$DEPSNEEDED $i"
	fi
done
if [[ "$DEPSNEEDED" != "" ]];then 
	echo -n "Please install the following dependencies: "
	echo "$DEPSNEEDED"
	exit 3
fi
###################################
###################################

[[ -z $PATHTOPLAYER ]] && PATHTOPLAYER=./ROCKBOX && TARG=testing #testing code.
#TODO: find a way to autodetermine $PATHTOPLAYER and mount status
if [[ "$TARG" != "testing" ]];then #there is a mounted player to worry about.
	mount |grep $PATHTOPLAYER >/dev/null
	if [[ $? -ne 0 ]];then #$PATHTOPLAYER is not mounted.
		echo "No drive mounted on $PATHTOPLAYER."
		echo "Please plug in the player and try again"
		exit 2
	fi
fi

# not actually using this variable at present
[[ -d $PATHTOPLAYER/.rockbox ]] && ROCKBOXPRESENT=YES || ROCKBOXPRESENT=NO

ROCKBOXINFO=$PATHTOPLAYER/.rockbox/rockbox-info.txt 

#http://download.rockbox.org/daily/build-info
URL=http://download.rockbox.org
BUILD=daily

# crude way to check if connected to internet
echo -n "Checking Internet Connectivity..."
ping -c1 rockbox.org >/dev/null
if [[ $? -ne 0 ]];then #not connected to internet.
	echo "Can\'t connect to internet."
	exit 1
fi
echo "Done!"

##TODO: Is there a better way of doing this which doesn't require lynx?
##TODO: should I use wget to download build-info and then parse it?
##TODO: If so, I will have to delete build-info after parsing it.
ONLINEINFO=`lynx -dump $URL/$BUILD/build-info`
# confirm lynx got proper info. If not, create $DATE from less reliable method
echo $ONLINEINFO |grep  \[dailies\] >/dev/null
if [[ $? -ne 0 ]];then #$ONLINEINFO is not the actual build-info output
	ONLINEINFO="date = \"`date -u +%Y%m%d`\""
fi

DATE=`echo $ONLINEINFO |grep date |grep -E -o "[0-9]{8}"`

# find out if version of rockbox already on player is latest.
# autodetermine $MODEL if possible
# if $ROCKBOXINFO doesn't exist, this version of rockbox is older than April 22,
# or else Rockbox has never been installed.
if [[ -r $ROCKBOXINFO ]];then #rockbox build later than 04/22/2007 is installed
	MODEL=`cat $ROCKBOXINFO |grep Target: |cut -f2 -d" "`
	ALREADY=$(echo 20`cat $ROCKBOXINFO |grep Version |cut -f2 -d-`)
else
	#$MODEL is already set at top of script
	#setting $ALREADY to 0 guarantees it is less than $DATE
	ALREADY=0
fi

FILE=rockbox-$MODEL-$DATE.zip

if [[ $ALREADY -lt $DATE ]];then  #version on player older than latest?
	#See if file already exists on computer before downloading
	if [[ ! -e $FILE ]];then #download file since it isn't on the computer
		wget $URL/$BUILD/$MODEL/$FILE
		if [[ $? -ne 0 ]];then #wget failed to download the file
			echo "wget did not download $URL/$BUILD/$MODEL/$FILE"
			echo "Please make sure you used the correct name for the MODEL variable."
			exit 4
		fi

	fi
	unzip -t $FILE >/dev/null  
	if [[ $? -eq 0 ]];then  #$FILE exists and is not corrupt 
		echo "Extracting $FILE to $PATHTOPLAYER..."
		unzip -oq $FILE -d $PATHTOPLAYER
		if [[ $? != 0 ]];then #make sure uzip worked
			#if can't write to $PATHTOPLAYER, this won't work
			echo "$FILE did not unzip to $PATHTOPLAYER."
			echo "This could be a permissions issue."
		fi
	else
		#delete $FILE. script will not update player.
		echo "$FILE is missing or corrupted. Please try again."
		rm $FILE
	fi
fi

[[ -r $ROCKBOXINFO ]] && NOW=$(echo 20`cat $ROCKBOXINFO |grep Version |cut -f2 -d-`) || NOW=0
if [[ $NOW -eq $DATE ]];then  #player is up-to-date
	echo "Player has latest version of Rockbox."
	# Get rid of older builds after we update the player.
	for i in rockbox-${MODEL}-*.zip
	do
		#it is possible for no file to be downloaded if the latest
		#version is already on the mp3 player. In that case, the
		#'! -e "$i"' prevents the program from trying to delete a file
		#that doesn't exist
		[[ "$i" == "$FILE" || ! -e "$i" ]] ||  rm $i
	done
else
	echo "Player does not have latest version of Rockbox."
fi
