Saturday, November 14, 2009

Cellular Phone Backup Script

As promised, here it is (commentary follows):
#! /bin/bash


delay=2 # time (in seconds) to wait between each phone access

grep port= $HOME/.gammurc | cut -d= -f2 |
while read phone
name="$(grep -m $(( $section + 1 )) name= $HOME/.gammurc | tail -1 | sed s/name=//)"
echo $name

rm -rf /tmp/$phone
mkdir -p /tmp/$phone
mkdir -p "$backup/$phone"
cd /tmp/$phone

# backup photos
gammu -s $section getfolderlisting $photos_root | grep "$photos_root" | sort |
while read filerecord
phone_path=$(echo $filerecord | cut -d\; -f1)
file=$(echo $filerecord | cut -d\; -f3 | sed s/\"//g)
timestamp=$(date -d "$(echo $filerecord | cut -d\; -f4 | sed s/\"//g)" +'%s')
size=$(echo $filerecord | cut -d\; -f5)
echo $file

# copy file from phone if not found on disk or has different size and/or timestamp
if [[ ! ( -e $local_path && \
"$timestamp $size" == "$(stat --format='%Y %s' $local_path)" ) ]]; then
sleep $delay
gammu -s $section getfiles "$phone_path" 2>/dev/null

# backup phone settings
sleep $(( $delay * 2 ))
# the first no is to save backup in ascii not unicode
# the second no is to disable broken backup of contacts in SIM (gammu bug?)
gammu -s $section --backup settings.backup 2>/dev/null <<EOF
# # backup sms
# # disabled - seems to hang waiting for phone
# sleep $delay
# gammu -s $section --backupsms sms.backup
cd - > /dev/null
rsync -avz /tmp/$phone $backup
let section++
My initial plan was to backup photos, contacts, settings and SMS contents, but I've hit several problems which made the script so ugly:
  1. Gammu fails to copy contacts from the SIM card on our phones (Nokia 2600) - I decided to only backup the contacts from the phone memory, which meant that I had to synchronize the contacts list on the phone memory with that on the SIM card
  2. Gammu hangs while trying to retrieve SMS contents from my wife's phone - I've decided not backup SMS contents
  3. photo retrieval is slow - so I complicated my script to make sure that I only retrieve new photos
  4. photo retrieval is prone to failure - waiting a second or two before each transfer seems to make communications much more robust

Phone contents is copied over to a backup directory whose name is determined by the port entry in each phone's settings section inside ~/.gammurc - which, in my case, is the Bluetooth address of the phone. You may want to use the name entry instead.

And, in case it isn't obvious, you must have a settings section for each phone being backed up, inside ~/.gammurc. The easiest way to do this is to let the Wammu phone setup wizard guide you.

Gammu comes with a Python library, which I might use someday for rewriting this script in Python. The main benefit would be that communications with each phone would only need to be initiated once, potentially making the whole process both faster and more reliable.

No comments:

Post a Comment