#!/system/xbin/busybox sh
# NOTE: if the memory card is mounted with the noexec flag, you will need
# to do the shell invocation by hand every time.
# Now, all these files are owned by their respective owners, and "adb pull"
# does not have permission for any of them.  Recover the content by
# unmounting the memory card and mounting it via USB.  

umask 022
broot=/sdcard/BackupRoot
mkdir -p $broot

opt_r=saving
while [ X$1 != X ] ; do
    case X$1 in
	X-n ) would="echo would " ; ;;
	X-r ) opt_r=restoring ; ;;
	X-a ) opt_a=1 ; ;;
	X ) : ; ;;
	* ) echo "Bad switch, usage: backup.sh [-n] [-r] [-a] (for test, to restore, all apps)"
	    exit 4
	    ;;
    esac
    shift
done

# Does the backup or restore according to opt_r and opt_n, for one file.
# Arg: the file.
bkup () {
    echo "$opt_r $1"
    if [ "$opt_r" != "restoring" ] ; then
	$would cp -p $1 $broot
    else
	$would cp -p $broot/$1 $1
    fi
}

# Does the backup or restore of a directory recursively.  Arg: the dir.
bkupr() {
    echo "$opt_r $1/"
    if [ "$opt_r" != "restoring" ] ; then
	src=$1
	tgt=$broot
    else
	src=$broot/$1
	mkdir -p $1
	tgt=$1/..
    fi
    for f in $src/* ; do
	if [ -h $f ] ; then
	    :	# Ignore symlinks entirely, like to the Gears dir
	else
	    $would cp -rp $src $tgt
	fi
    done
}

if [ -n "$opt_a" ] ; then
    # Save all the downloaded applications.
    bkupr /data/app
    # Save all the data that goes with downloaded and distro applications.
    bkupr /data/data
fi

# Save alarm clock
bkup /data/data/com.android.alarmclock/databases/alarms.db
# Save browser data (bookmarks etc)
bkup /data/data/com.android.browser/databases/browser.db
# Save SMS message history
bkup /data/data/com.android.providers.telephony/databases/mmssms.db
# Save user dictionary
bkup /data/data/com.android.providers.userdictionary/databases/user_dict.db
# Save all settings
bkup /data/data/com.android.settings/shared_prefs/com.android.settings_preferences.xml
# Save vendor assets (purchase record at Android Market?)
bkup /data/data/com.android.vending/databases/assets.db
# Save applications configuration
bkup /system/etc/apns-conf.xml 

# Special for jimc
for g in /sdcard/*.dat ; do
    bkup $g
done
