#!/bin/sh
#
# This script grabs MSL rawimages from the NASA website
# Usage: ./MSLget.sh <number of sol>
# Example: ./MSLget.sh 3 will grab all images made on sol 3

#
# Clear the screen
#

clear

#
# Set the variabeles
#

MSLHOME=${HOME}/MSL
DATADIR=${MSLHOME}/images
TMPDIR=${MSLHOME}/tmp
SOL=${1}

#
# Check if a sol has been given as an argument
#

if [ -z ${SOL} ]

then

	echo "Usage: ./MSLget.sh <number of sol>"
	echo "Example: ./MSLget.sh 3 will grab all images made on sol 3"
	echo "Press <enter> to exit \c"
	read KEYPRESS
	exit
fi

#
# RoverDriver pointed out that not every system comes with wget
# Let's handle that gracefully
#

which wget  

if [ ${?} -ne 0 ]

then

	echo "You need to have wget installed on your system and in your \${PATH}" 
	echo "Press <enter> to exit \c"
	read KEYPRESS
	exit

fi

#
# check if the datadir exists. if not create it
#

if [ ! -d ${DATADIR} ]

then

	mkdir -p ${DATADIR}
fi

#
# Check if the tempdir exsists, if not create it
#

if [ ! -d ${TMPDIR} ]

then

	mkdir -p ${TMPDIR}

fi

#
# Mandevil asked for leading zeros in the sol's directory name
# Here we go
#

LENGTH=`echo ${SOL} | wc -c`

case ${LENGTH} in

2)
	SOLDIR=`echo 000${SOL}`
	;;

3)	SOLDIR=`echo 00${SOL}`
	;;

4)	SOLDIR=`echo 0${SOL}`
	;;

5)	SOLDIR=`echo ${SOL}`
	;;

esac

#
# Check if the directory for the sol we're grabbing exists
# if not we create it
#

if [ ! -d ${DATADIR}/${SOLDIR} ]

then

	mkdir -p ${DATADIR}/${SOLDIR}

fi

#
# Clean the tempdir
#

rm  ${TMPDIR}/*

#
# We grab a list of all the images for this sol
#

wget http://mars.jpl.nasa.gov/msl/multimedia/raw/?s=${SOL} --directory-prefix=${TMPDIR}
cat $TMPDIR/index.html\?s\=${SOL} | grep msl-raw-images | awk -F\<img\ src=\" '{ print $2 }' | awk -F\" '{ print $1 }' | sort | uniq > ${TMPDIR}/images.${SOL}.txt  

#
# Now we get all the images that are available only as thumbnails
# This are images that DON'T have thm.jpg in their name
# 

grep -v thm\.jpg ${TMPDIR}/images.${SOL}.txt > ${TMPDIR}/images_to_get.txt

#
# Now we get the images that are available in a larger size
# This are image that DO have thm.jpg in their name
#

grep thm\.jpg ${TMPDIR}/images.${SOL}.txt | awk -F\-thm.jpg '{ print $1".JPG" }' >> ${TMPDIR}/images_to_get.txt

#
# Time to fetch the GOOD stuff..
#

wget -nc --directory-prefix=${DATADIR}/${SOLDIR} -i ${TMPDIR}/images_to_get.txt 

#
# All done, now be a nice guy and clean all up
#

rm  ${TMPDIR}/*
