#!/bin/sh
#

adb kill-server
adb devices
if [ $? != 0 ]; then
    echo -e "\nFreerunner NOT found. Exit\n"
    exit 1
else
    if [ `adb devices | grep offline` ]; then
	echo -e \"\nERROR: Freerunner NOT found. Exiting\n\"
	exit 1;
    fi
fi

build_date=`echo "$(date +%Y%m%d-%I%M%S)"`

dir_name=neo-$build_date

echo "Saving contacts and mms into: $dir_name"

if [[ -d $dir_name ]]; then
    echo "Error $dir_name allready exists. Run $0 again."
    echo
    exit -1
else
    mkdir $dir_name
	
	echo -e "\n========================= Backup /data/data/ =========================\n"
    adb pull /data/data/ $dir_name/data/
    
    # old database for browser can cause problems so we remove them
    rm -f $dir_name/data/com.android.browser/databases/*
    
    #another option is to pull-push only needed files
    #adb pull /data/data/com.android.providers.contacts/databases/contacts.db $dir_name/contacts.db
    #adb pull /data/data/com.android.providers.telephony/databases/mmssms.db $dir_name/mmssms.db
    #adb pull /data/data/com.android.alarmclock/databases/alarms.db $dir_name/alarms.db
    #adb pull /data/data/com.android.providers.settings/databases/settings.db $dir_name/settings.db
    #adb pull /data/data/com.android.providers.calendar/databases/calendar.db $dir_name/calendar.db
    #adb pull /data/data/com.android.settings/ $dir_name/com.android.settings/
    #adb pull /data/data/com.android.settings/shared_prefs/com.android.settings_preferences.xml $dir_name/com.android.settings_preferences.xml
    #adb pull /data/data/org.andnav2/ $dir_name/org.andnav2/

    echo "#!/bin/bash
#
thisdir=\$PWD

adb kill-server
adb devices | grep \"emulator-5554\"
if [ \$? != 0 ]; then
    echo -e \"\nERROR: Freerunner NOT found. Make shure to check \nSettings->Applications->Development->USBDebugging and\nSettings->Applications->Development->Stay awake \nExiting\n\"
    exit 1
fi

adb devices | grep \"offline\"
if [ \$? = 0 ]; then
	echo -e \"\nERROR: Freerunner found but it is offline. Please disconect and reconnect.\nExit\n\"
	exit 1
fi

echo -e \"\n=== Installing busybox ===\n\"

list=\"[, [[, acpid, addgroup, adduser, adjtimex, ar, arp, arping, ash, awk, basename, blkid, brctl, bunzip2, bzcat, bzip2, cal, cat, catv, chat, chattr, chgrp, chmod, chown, chpasswd, chpst, chroot, chrt, chvt, cksum, clear, cmp, comm, cp, cpio, crond, crontab, cryptpw, cttyhack, cut, date, dc, dd, deallocvt, delgroup, deluser, depmod, devmem, df, dhcprelay, diff, dirname, dmesg, dnsd, dos2unix, du, dumpkmap, dumpleases, echo, ed, egrep, eject, env, envdir, envuidgid, ether-wake, expand, expr, fakeidentd, false, fbset, fbsplash, fdflush, fdformat, fdisk, fgrep, find, findfs, fold, free, freeramdisk, fsck, fsck.minix, ftpd, ftpget, ftpput, fuser, getopt, getty, grep, gunzip, gzip, halt, hd, hdparm, head, hexdump, hostid, hostname, httpd, hush, hwclock, id, ifconfig, ifdown, ifenslave, ifup, inetd, init, insmod, install, ionice, ip, ipaddr, ipcalc, ipcrm, ipcs, iplink, iproute, iprule, iptunnel, kbd_mode, kill, killall, killall5, klogd, last, length, less, linux32, linux64, linuxrc, ln, loadfont, loadkmap, logger, login, logname, logread, losetup, lpd, lpq, lpr, ls, lsattr, lsmod, lzmacat, makedevs, makemime, man, md5sum, mdev, mesg, microcom, mkdir, mkdosfs, mkfifo, mkfs.minix, mkfs.vfat, mknod, mkpasswd, mkswap, mktemp, modprobe, more, mount, mountpoint, msh, mt, mv, nameif, nc, netstat, nice, nmeter, nohup, nslookup, od, openvt, passwd, patch, pgrep, pidof, ping, ping6, pipe_progress, pivot_root, pkill, popmaildir, poweroff, printenv, printf, ps, pscan, pwd, raidautorun, rdate, rdev, readahead, readlink, readprofile, realpath, reboot, reformime, renice, reset, resize, rm, rmdir, rmmod, route, rtcwake, run-parts, runlevel, runsv, runsvdir, rx, script, sed, sendmail, seq, setarch, setconsole, setfont, setkeycodes, setlogcons, setsid, setuidgid, sh, sha1sum, sha256sum, sha512sum, showkey, slattach, sleep, softlimit, sort, split, start-stop-daemon, stat, strings, stty, su, sulogin, sum, sv, svlogd, swapoff, swapon, switch_root, sync, sysctl, syslogd, tac, tail, tar, tcpsvd, tee, telnet, telnetd, test, tftp, tftpd, time, timeout, top, touch, tr, traceroute, true, tty, ttysize, tunctl, udhcpc, udhcpd, udpsvd, umount, uname, uncompress, unexpand, uniq, unix2dos, unlzma, unzip, uptime, usleep, uudecode, uuencode, vconfig, vi, vlock, watch, watchdog, wc, wget, which, who, whoami, xargs, yes, zcat, zcip\"

IFS=\", \"
dir=\"/data/local/bin\"

adb shell \"mkdir \$dir\"
adb push busybox \$dir/busybox
adb shell \"chmod 744 \$dir/busybox\"
echo \"\"

for cmd in \$list
do
    echo \"ln -s busybox \$cmd\"
    adb shell \"cd \$dir; ln -s busybox \$cmd\"
    #echo \" \"
done

echo -e \"\n=== Installing ES File Explorer ===\n\"
adb install -r \"../es_file_explorer.apk\"

echo -e \"\n=== Restoring settings ===\n\"

#another option is to pull-push only needed files
adb push data/ /data/data/

echo -e \"\n=== Restoring date & time ===\n\"

DATE_YEAR=\$(date +%Y)
DATE_MONTH=\$(date +%m)
DATE_DAY=\$(date +%e)

TIME_HOUR=\$(date +%H)
TIME_MINUTES=\$(date +%M)
TIME_SECONDS=\$(date +%S)

echo -e \"Setting Second to:\t\$TIME_SECONDS\"
echo -e \"Setting Minute to:\t\$TIME_MINUTES\"
echo -e \"Setting Hour to:  \t\$TIME_HOUR\n\"

echo -e \"Setting Day to:  \t\$DATE_DAY\"
echo -e \"Setting Month to:\t\$DATE_MONTH\"
echo -e \"Setting Year to: \t\$DATE_YEAR\n\"

# next 2 lines are here to fix some bugs in busybox->date
((DATE_DAY++))
((TIME_HOUR=24-TIME_HOUR))
echo -e \"WARNING: Be shure to check and correct day and hour because I am too stupid to set it up properly\n\"

adb shell \"\$dir/date -s \$DATE_YEAR-\$DATE_MONTH-\$DATE_DAY-\$TIME_HOUR:\$TIME_MINUTES:\$TIME_SECONDS\"
adb shell \"\$dir/hwclock -w\"
adb shell \"\$dir/date\"

echo -e \"\n========================= DONE =========================\n\t(but need a reboot now ...)\n\"

adb shell \"reboot\" &
adb kill-server

" > $dir_name/restore.sh
    chmod +x $dir_name/restore.sh

    # preinstall busybox ... if needed
    if  [ -x busybox ]; then
		ln -s ../busybox $dir_name/busybox
    else
		wget "http://verdebreuk.googlecode.com/files/busybox" -O busybox
		chmod +x busybox
		if [ $? != 0 ]; then
	    	echo -e "WARNING: I could not find busybox locally or on the net\n\tTry to put it here manually or some parts of the restore script will fail.\n"
		fi
    fi
    
    if [ ! -e es_file_explorer.apk ]; then
    	wget "http://slideme.org/mobileapp/download/b6dfdb94-0841-102d-a134-12313a00d126.apk" -O es_file_explorer.apk
    	if [ $? != 0 ]; then
	    	echo -e "WARNING: Can not get ES File Explorer\n"
		fi
	fi
fi

echo -e "\n========================= DONE =========================\n"

