#!/bin/bash
oldifs=$IFS
IFS=$'\n'
sdcard="/storage/emulated/0"
destdir="/home/wytrzeszcz/nfs/backups/phone"
pidfile=/var/lock/android
function crash()
{

	echo "ANDROID COPY FAIL $1 $(date)">>/var/log/android
	exit 1
}
function succes()
{

	echo "ANDROID COPY OK $1 $(date)">>/var/log/android
}
echo "ANDROID COPY START I $(date)">>/var/log/android
adb shell id  || crash "NO PHONE"
if [ -f "$pidfile" ] && kill -0 `cat $pidfile` 2>/dev/null; then
    crash "STILL RUNNING"
fi  
echo $$ > $pidfile
mkdir -p $destdir || crash "DESTDIR" 
mkdir -p /tmp/android
cd /tmp/android || crash "CD"
adb shell find $sdcard/mark || adb shell touch -d 1970-01-0100:00:00 $sdcard/mark

succes "MAKE MARK"

for dir in $(adb shell find  /storage -type d -newer $sdcard/mark | sed "s|^|$destdir|")
do
	mkdir -p $dir || crash "MKDIR STORAGE"
done
succes "MAKE DIR STORAGE"
for file in $(adb shell find  /storage -type f -newer $sdcard/mark)
do
	filename=$(basename $file)
	dest=$(echo $file|sed "s|^|$destdir|");
	adb pull $file || crash "PULL STORAGE"
	mv "/tmp/android/$filename" "$dest" || crash "MV STORAGE"
done
succes "COPY STORAGE"
for dir in $(adb shell find  $sdcard -type d -newer $sdcard/mark | sed "s|^|$destdir|")
do
	mkdir -p $dir || crash "MKDIR CARD"
done
succes "MAKE DIR CARD"
for file in $(adb shell find  $sdcard -type f -newer $sdcard/mark)
do
	filename=$(basename $file)
	dest=$(echo $file|sed "s|^|$destdir|");
	adb pull $file || crash "PULL CARD"
	mv "/tmp/android/$filename" "$dest" || crash "MV CARD"
done
succes "COPY CARD"
adb shell rm $sdcard/mark
adb shell touch $sdcard/mark
IFS="$oldifs"
