#!/bin/tcsh

set takeOneNow     = 0                             ## Normally 0, 1 = photo now
set theVerbose     = 0                             ## 1=print status
set theSleepSecs   = 0                             ## 19 for 30sec/frame

set theDateRaw     = `date '+%a%F@%R:%S'`           ## Wed2004-12-01@22:20:23
set theDayName     = `echo $theDateRaw | cut -c1-3` ## Wed
set theDate        = `echo $theDateRaw | cut -c4-`  ## 2004-12-01@22:20:23
set theDay         = `echo $theDate | cut -c-10`    ## 2004-12-01
set theFile        = $theDate.jpg                   ## 2004-12-01@22:20:23.jpg
set theWWWbase     = CITRIStl
set theWWWsmall    = $theWWWbase-Small.jpg
set theWWWlast     = $theWWWbase-Last.jpg
set theHost        = "nim.cs.berkeley.edu"
set theTLdir       = "/home/eecs/ddgarcia/w/tl"

set theStartHour   = "06" # 06
set theStartMinute = "00" # 00
set theEndHour     = "17" # 17
set theEndMinute   = "30" # 30

set theHour        = `echo $theDate | cut -c12-13`  ## 22
set theMinute      = `echo $theDate | cut -c15-16`  ## 35

## If we're after-hours OR on Saturday or Sunday, no photos, rest...
if (  (! $takeOneNow) && \
      ( ($theHour < $theStartHour) || \
        (($theHour == $theStartHour && $theMinute < $theStartMinute)) || \
        ($theHour > $theEndHour) || \
        (($theHour == $theEndHour && $theMinute >= $theEndMinute)) || \
        ($theDayName == "Sat") || \
        ($theDayName == "Sun")) )  then
   echo "Zzz...("$theHour":"$theMinute") not between ("$theStartHour":"$theStartMinute") and ("$theEndHour":"$theEndMinute")...sleeping another minute"
   sleep 60

else ## if NOT after-hours

   if ($theVerbose) echo "(0) mkdir i/$theDay if it didn't exist"
   if (! -e i/$theDay) mkdir i/$theDay
   
   if ($theVerbose) echo "(1) Telling camera to take photo"
   gphoto2 --capture-image
   
   if ($status == 0) then
   
      if ($theVerbose) echo "(2) Downloading photo from camera to i/$theDay/$theFile"
      gphoto2 -P --filename i/$theDay/$theFile
   
      if ($theVerbose) echo "(3) Deleting photo from camera"
      gphoto2 -D -R
   
      if ($theVerbose) echo "(4) Shift current NFS thumb to last AND make new NFS thumb"
      ( mv $theTLdir/$theWWWsmall $theTLdir/$theWWWlast ; \
        cat i/$theDay/$theFile | djpeg -scale 1/4 | cjpeg -quality 75 >! $theTLdir/$theWWWsmall ) &
   
      if ($theVerbose) echo "(5) Copy the original to the web"
      cp   i/$theDay/$theFile $theTLdir/$theWWWbase.jpg &
   
      if ($theVerbose) echo "(6) Sleep for $theSleepSecs seconds"
      if (! $takeOneNow) sleep $theSleepSecs
   
      if ($theVerbose) echo "(7) Done, returning to caller (prob tl.csh)"
      exit 0
   
   else ## if $status==0 (i.e., bad photo)
   
      echo "Camera down at $theFile! sleeping..."
      echo "date +'%m-%d@%R' | m tl ddgarcia@cs.berkeley.edu" | ssh $theHost >& /dev/null
      sleep 16000000
      exit 1
   
   endif ## if $status==0 (i.e., bad photo)
endif ## if after-hours
