#!/usr/bin/python
# timelapse motion detection, caching part
# 1.10.2009 by Nick Fankhauser
# Requires motion_detect (compiled from motion_detect.c) in PATH
import os,sys

# zytglogge cam
#logfile='/root/bin/motion_detect_cache.py.log'
#target='/mnt/max/nick/kg/'
# balkon cam
logfile='/root/balkon_motion.txt'
target='/mnt/max/video/philme/balkon_sorted/'

def logg(x):
 if os.path.isfile(logfile): mode='a'
 else: mode='w'
 open(logfile,mode).write(x+'\n')
 return x

def get_map_dict():
 md={}
 if not os.path.isfile(logfile): return md
 for l in open(logfile):
  lsp=l.strip().split('\t')
  md[lsp[0]]=lsp[1]
 return md

def scanDir(d):
 rl=[]
 for fn in os.listdir(d):
  if os.path.isdir(d+fn): rl+=scanDir(d+fn+'/')
  else: rl.append(d+fn)
 return rl

motion_detect=lambda x,y : int(os.popen('motion_detect %s %s' % (x,y)).read().strip())
mapdict=get_map_dict()
fl=filter(lambda x:'.jpg'==x[-4:],scanDir(target))
fl.sort()
for i in range(len(fl)-1):
 n1,n2=fl[i],fl[i+1]
 k='%s-%s' % (n1,n2)
 if mapdict.has_key(k): continue
 print logg( '%s-%s\t%d' % (n1,n2,motion_detect(n1,n2)) )