#!/bin/bash
# To restore all the apps from /data/app plus their data from /data/data.  
# This directory (where you backed up your *.apk files) is required on the 
# command line.  Suggested command line to capture output with possible errors:
#   insapps.sh backupdir/data/app 2>&1 | tee /tmp/insapps.log
# If the apk file is called backupdir/data/app/com.example.nameofapp.apk
# then the data is expected in backupdir/data/data/com.example.nameofapp

# This program assumes that all the saved apps are to be installed, i.e.
# no apps were left on the device when installing the new OS image.  
# This program does not restore any data from apps included with the system
# (like system settings).  

# Run this as root, because Android sets wacko permissions and an ordinary
# user won't be able to read the data.  


if [ -z "$1" -o ! -d "$1" ] ; then
    echo "Directory containing backed-up apps is required on command line."
    exit 4
fi

tarf=/tmp/insapps.tar
datadir=${1%/app}/data
for f in $1/*.apk ; do
    bname=${f%.apk}
    bname=${bname##*/}
    data=$datadir/$bname
    if [ ! -d $data ] ; then
	bname=${bname%-[0-9]*}
	data=$datadir/$bname
    fi
    case $bname in
	com.android.vending | com.google.earth | com.koushikdutta.rommanager )
	    echo "In CM9, skipped: $bname"
	    continue
	    ;;
	* )	: ; ;;
    esac
    echo Installing app: $f
    adb install $f
    if [ ! -d $data ] || /bin/true ; then
	echo "No data: $data"
    else
	echo Installing data: $bname
	( cd $datadir && \
	    tar cf $tarf $bname && \
	    adb push $tarf $tarf && \
	    adb shell "cd /data/data && tar xpf $tarf" )
    fi
done
