#!/bin/sh
# \
exec oagwish "$0" "$@"

set auto_path [linsert $auto_path 0 /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0  /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSDebugPath

set CVSRevisionAuthor "\$Revision: 1.0 $ \$Author: gfystro $"

wm geometry . +25+25

set removePics 1
set resizePics 1
set destination "web"
set otherDirectory "/home/helios/ASDOPS"
set mainStatus "Initializing..."
set phoneDir "/media/9016-4EF8/DCIM/100KYOCE"
set tempDirectory "/tmp/ASDOPS_Phone_Pics"
set oldFileDate [clock format [clock scan {30 days ago}] -format "%Y%m%d%H%M%S"]
set cameraPictureList {}
set rootWebDir "/home/helios/ASDOPS/logbook/html/daily"
set rootAsdopsDir "/home/helios/ASDOPS/daily"
#	set timestamp [clock seconds]
#	set year [clock format $timestamp -format "%Y"]
#	set month [clock format $timestamp -format "%m"]
#	set day [clock format $timestamp -format "%d"]
#	set longDate [clock format $timestamp -format "%Y%m%d%H%M%S"]
#	set dirWebYear "$rootWebDir/$year"
#	set dirAsdopsYear "$rootAsdopsDir/$year"
#	set dirWebMonth "$rootWebDir/$year/$month"
#	set dirAsdopsMonth "$rootAsdopsDir/$year/$month"
#	set dirWebDay "$rootWebDir/$year/$month/$day"
#	set dirAsdopsDay "$rootAsdopsDir/$year/$month/$day"
#	set webDir "$rootWebDir/$year/$month/$day"
#	set asdopsDir "$rootAsdopsDir/$year/$month/$day"

# sends output to the mainStatus widget
proc SetMainStatus {text} {
    global mainStatus
    set mainStatus $text
    update
}

# generates the daily directory names
proc SetDirDates {} {
	global longDate
	global dirWebYear
	global dirAsdopsYear
	global dirWebMonth
	global dirAsdopsMonth
	global dirWebDay
	global dirAsdopsDay
	global webDir
	global asdopsDir
	global rootWebDir
	global rootAsdopsDir
	set timestamp [clock seconds]
	set year [clock format $timestamp -format "%Y"]
	set month [clock format $timestamp -format "%m"]
	set day [clock format $timestamp -format "%d"]
	set longDate [clock format $timestamp -format "%Y%m%d%H%M%S"]
	set dirWebYear "$rootWebDir/$year"
	set dirAsdopsYear "$rootAsdopsDir/$year"
	set dirWebMonth "$rootWebDir/$year/$month"
	set dirAsdopsMonth "$rootAsdopsDir/$year/$month"
	set dirWebDay "$rootWebDir/$year/$month/$day"
	set dirAsdopsDay "$rootAsdopsDir/$year/$month/$day"
	set webDir "$rootWebDir/$year/$month/$day"
	set asdopsDir "$rootAsdopsDir/$year/$month/$day"
}

# verify/create temp dir and clean up old files
proc TempDirCheck {} {
	global tempDirectory
	# check that the tmp directory exists, if not, create it
	if ![file isdirectory $tempDirectory] {
		SetMainStatus "creating $tempDirectory ..."
		file mkdir $tempDirectory
	} else {
		SetMainStatus "$tempDirectory exists."
	}
	# erase all jpgs in $tempDirectory that are older than one week 
	set tempOldList [glob -nocomplain -directory $tempDirectory *.JPG]
	if {[llength $tempOldList]} {
		SetMainStatus "Found temp files..."
		CleanUpOldPics $tempOldList
		SetMainStatus "Old temp files have been removed."
	} else {
		SetMainStatus "No old temp files to be cleaned out."
	}
}

# delete any files in the temp dir older than $oldFileDate
proc CleanUpOldPics {fileList} {
	global oldFileDate
	SetMainStatus "Removing pictures before $oldFileDate"
	foreach fileName $fileList {
		if { [string range [file tail $fileName] 0 13] < $oldFileDate } {
			SetMainStatus "Removing $fileName"
			file delete $fileName
		}
	}
}

# creates the appropriate web directories for organizing photos in daily folders
proc CreateWebDir {} {
	SetDirDates
	global rootWebDir
	global dirWebYear
	global dirWebMonth
	global dirWebDay
	global webDir
	global copyToDir
	if ![file isdirectory $rootWebDir] {
		SetMainStatus "Error: Could not find $rootWebDir \nE-mail this error to gfystro@aps.anl.gov"
		return false
	}
	if ![file isdirectory $dirWebYear] {
		SetMainStatus "$dirWebYear does not exist, creating it..."
		file mkdir $dirWebYear
	}
	if ![file isdirectory $dirWebMonth] {
		SetMainStatus "$dirWebMonth does not exist, creating it..."
		file mkdir $dirWebMonth
	}
	if ![file isdirectory $dirWebDay] {
		SetMainStatus "$dirWebDay does not exist, creating it..."
		file mkdir $dirWebDay
	}
	SetMainStatus "Selected directory is $webDir"
	set copyToDir $webDir
	return true
}

# creates the appropriate asdops directories for organizing photos in daily folders
proc CreateAsdopsDir {} {
	SetDirDates
	global rootAsdopsDir
	global dirAsdopsYear
	global dirAsdopsMonth
	global dirAsdopsDay
	global asdopsDir
	global copyToDir
	if ![file isdirectory $rootAsdopsDir] {
		SetMainStatus "Error: Could not find $rootAsdopsDir \nE-mail this error to gfystro@aps.anl.gov"
		return false
	}
	if ![file isdirectory $dirAsdopsYear] {
		SetMainStatus "$dirAsdopsYear does not exist, creating it..."
		file mkdir $dirAsdopsYear
	}
	if ![file isdirectory $dirAsdopsMonth] {
		SetMainStatus "$dirAsdopsMonth does not exist, creating it..."
		file mkdir $dirAsdopsMonth
	}
	if ![file isdirectory $dirAsdopsDay] {
		SetMainStatus "$dirAsdopsDay does not exist, creating it..."
		file mkdir $dirAsdopsDay
	}
	set copyToDir $asdopsDir
	SetMainStatus "Selected directory is $asdopsDir"
	return true
}

# checks that the other directory exists and is writable
proc CheckOtherDir {} {
	global otherDirectory
	global copyToDir
	global longDate
	set timestamp [clock seconds]
	set longDate [clock format $timestamp -format "%Y%m%d%H%M%S"]
	if {[catch { file attributes $otherDirectory } error]} { 
		SetMainStatus "$error"
		return false
	}
	set copyToDir $otherDirectory
	return true
}

# 
proc GetCameraPictureList {} {
	global phoneDir
	set fileList [glob -nocomplain -tails -directory $phoneDir *.JPG]
#	SetMainStatus "Pics found: $fileList"
	return $fileList
}

# 
proc CheckCameraPictures {} {
	global cameraPictureList
	global phoneDir
	set cameraPictureList [GetCameraPictureList]
	if {![llength $cameraPictureList]} {
		SetMainStatus "No cell phone photos found."
		APSDisableWidget .userFrame.copyButton
	} else {
		SetMainStatus "Cell phone photos found."
		APSEnableWidget .userFrame.copyButton
	}
}

proc CopyButtonGo {} {
	global phoneDir
	global tempDirectory
	global destination
	global resizePics
	global removePics
	global copyToDir
	# create desired directory
	if {$destination == "web"} {
		SetMainStatus "Checking web directory..."
		CreateWebDir
	} elseif {$destination == "asdops"} {
		SetMainStatus "Checking ASDOPS directory..."
		CreateAsdopsDir
	} elseif {$destination == "other"} {
		SetMainStatus "Checking other directory..."
		if {![CheckOtherDir]} {
			SetMainStatus "Failed to verify other directory."
			return false
		}
	} else {
		break
	}
	# create new pic file name list
	DestPictureList
	# if for each type of transfer
	if {!$resizePics} {
		if {!$removePics} {
			CopyPictures $phoneDir $tempDirectory
			CopyPictures $phoneDir $copyToDir
		} else {
			CopyPictures $phoneDir $tempDirectory
			MovePictures $phoneDir $copyToDir
		}
	} else {
		if {!$removePics} {
			CopyPictures $phoneDir $tempDirectory
			ConvertPictures $phoneDir $copyToDir
		} else {
			ConvertPictures $phoneDir $copyToDir
			MovePictures $phoneDir $tempDirectory
		}
	}
	CheckCameraPictures
	SetMainStatus "Copy process is complete."
	SetMainStatus "Done."
}

proc DestPictureList {} {
	global cameraPictureList
	global destPictureList
	global longDate
	set destPictureList {}
	foreach pic $cameraPictureList {
		lappend destPictureList "$longDate$pic"
	}
}

proc CopyPictures {fromDir toDir} {
	global cameraPictureList
	global destPictureList
	foreach original $cameraPictureList target $destPictureList {
		SetMainStatus "copying $fromDir/$original to $toDir/$target"
		file copy $fromDir/$original $toDir/$target
	}
}

proc ConvertPictures {fromDir toDir} {
	global cameraPictureList
	global destPictureList
	foreach original $cameraPictureList target $destPictureList {
		set cmd "convert -resize 768x768 -unsharp 0x0.75+0.75+0.008 $fromDir/$original $toDir/$target"
		SetMainStatus "converting $fromDir/$original to $toDir/$target"
		eval exec $cmd
	}
}

proc MovePictures {fromDir toDir} {
	global cameraPictureList
	global destPictureList
	foreach original $cameraPictureList target $destPictureList {
		SetMainStatus "copying $fromDir/$original to $toDir/$target"
		file copy $fromDir/$original $toDir/$target
		SetMainStatus "removing $fromDir/$original"
		file delete $fromDir/$original
	}
}

APSApplication . -name PhonePicImport -version $CVSRevisionAuthor -overview {This application is intended for copying pictures from an ASDOPS cell phone to a workstation, primarily for use in the logbook.}

APSScrolledStatus .status -parent .userFrame -textVariable mainStatus -width 48

APSRadioButtonFrame .action -parent .userFrame -label "\"Copy to\" Location" -variable destination -buttonList {"Logbook (html daily directory)" "ASDOPS daily directory" "Other"} -valueList {web asdops other} -commandList {"lassign {1 1} resizePics removePics; APSDisableWidget .userFrame.otherDir" "APSDisableWidget .userFrame.otherDir" "APSEnableWidget .userFrame.otherDir"} -contextHelp "Select the directory to which you wish to copy the pictures."

APSLabeledEntry .otherDir -parent .userFrame -label "Other Directory:" -textVariable otherDirectory -width 30 -fileSelectButton 1 -fileSelectDirectory 1 -contextHelp "Enter the full path to the desired directory."

APSCheckButtonFrame .options -parent .userFrame -buttonList {"Resize pictures to conserve space" "Remove pictures from device after copying"} -variableList {resizePics removePics} -label Options -contextHelp "Check these boxes to resize the image to a maximum dimension of 768px or to erase the pictures from the phone after transferring them to the new location."

APSDisableWidget .userFrame.otherDir

# copy button
APSButton .copyButton -parent .userFrame -text "Copy Pictures" -command "CopyButtonGo" -contextHelp "Click here to copy the pictures to the desired location. If this button is disabled, it usually indicates that there were no pictures found on the phone."

# reset button to call proc to check for files existing on camera, enable copy button if true
APSButton .resetButton -parent .userFrame -text "Reset" -command "CheckCameraPictures" -contextHelp "Use the reset button to search again for pictures on the phone."

# make sure the temp directory is ready
TempDirCheck

# check if there are images on the camera
CheckCameraPictures

SetMainStatus "Ready."


# convert -resize 768x768 -unsharp 0x0.75+0.75+0.008 original.JPG converted.JPG


## process procedure
## if destination == other verify otherDirectory is directory, set copyToDir otherDirectory
