#!/bin/bash

# Download specific filetypes from mobile devices
# using Gammu for backup purposes.

# Modify "Variable Declarations" to coincide with your file system.
# Also, make sure the tempfile location is writable and I have
# more then one device within my ~/.gammurc file -- as such,
# I'm reading in the second device configured within gammurc.

# Roger  roger@eskimo.com
# CVS: $Header

# Variable Declarations
shopt -s -o nounset
declare -rx GAMMURC_ENTRY="2"
declare -i COUNTER
declare -rx cat="/usr/bin/cat"
declare -rx cut="/usr/bin/cut"
declare -rx date="/usr/bin/date"
declare -x FILES
declare -x file
declare -x FOLDER
declare -rx gammu="/usr/bin/gammu"
declare -rx grep="/bin/grep"
declare -rx mkdir="/bin/mkdir"
declare -rx rm="/bin/rm"
declare -rx tempfile_01="/tmp/filesystem_01.tmp"


# Sanity Checks
if test ! -x "$gammu" ; then
	printf "$SCRIPT:$LINENO: the command $gammu is not available -\
	please install app-mobilephone/gammu - aborting\n " >&2
fi

get_filesystem()
# Retrieve the flat filesystem from device for parsing
{
$rm -f $tempfile_01
$gammu $GAMMURC_ENTRY --getfilesystem -flatall > $tempfile_01
}

get_images()
# Function filters only images and gets their assigned file number.
{
{ while read file ; do
	echo $file |
	grep Images |
	grep -iE '\.gif|\.jpg|\.png' |
	cut -f 1 --delimiter=";" |
	sed -e "s/^//" | tr '\n' ' '
done } < $tempfile_01
}

get_java()
# Function filters only images and gets their assigned file number.
{
{ while read file ; do
	echo $file |
	grep -iE '\.jad|\.jar' |
	cut -f 1 --delimiter=";" |
	sed -e "s/^//" | tr '\n' ' '
done } < $tempfile_01
}


# Main

# Get the filesystem to tempfile and create base folder
get_filesystem
FOLDER="gammu-backup."`$date +%Y%m%d`
$mkdir $FOLDER
cd $FOLDER

# Retrieve all images
$mkdir ./images
cd ./images
FILES=`get_images`
$gammu $GAMMURC_ENTRY --getfiles $FILES
cd ../

# Retrieve all java apps
$mkdir ./java
cd ./java
FILES=`get_java`
$gammu $GAMMURC_ENTRY --getfiles $FILES
cd ../

# Retrieve all PIM data
(echo no; echo ALL) | $gammu $GAMMURC_ENTRY --backup pim.`$date +%Y%m%d`
cd ../

# Tarball this folder
tar -jcpvf $FOLDER.tar.bz2 ./$FOLDER

# Cleanup
$rm -f $tempfile_01

exit 0

