#!/bin/bash

WhiteBoardCamera="/dev/v4l/by-id/usb-046d_C922_Pro_Stream_Webcam_511379DF-video-index0"

HugoBaseDir="/home/pgadey/Hugo/pgadey/";
HugoPhotoDir="/home/pgadey/Hugo/pgadey/static/images/office-camera/";
HugoMarkdownDir="/home/pgadey/Hugo/pgadey/content/office-camera/";
HugoImagePrefix="/images/office-camera/";
HugoPostScript="/home/pgadey/Hugo/pgadey/post.sh"

TempDir="/tmp/"

shootImage () {
	# set times based on image file
	IsoTime=$(date --iso=second);
	CurrentTime=$(date +%Y-%m-%d\ @\ %H:%M:%S)

	ImageFile="$IsoTime.jpeg";

	echo -e "Shooting image and storing it: $TempDir$ImageFile\n";

	# shoot a photo and silence all output
	#streamer -c $WhiteBoardCamera -o $TempDir$ImageFile -j 100 -s 800x600 &> /dev/null ## lower-resolution
	streamer -c $WhiteBoardCamera -o $TempDir$ImageFile -j 100 -s 960x720  &> /dev/null ## higher-resolution
	
	# show a preview of the photo and return to script
	feh --scale-down $TempDir$ImageFile &

	# capture the PID of feh, so we can close it after preview
	FehPID=$!;
	echo -e "PID of feh is: $FehPID\n";
}

makeMarkdown () {
	MarkdownFile="$IsoTime.md";
	Title=${1:-$CurrentTime}; # if there is no title, default to the date
	echo -e "Creating markdown with title: $Title\n";

HugoMd="---
title: \"$Title\"
date: $IsoTime
tags: ['office camera']
---
![A photo of a whiteboard titled: $Title]($HugoImagePrefix$ImageFile \"$Title\")"

	echo -e "Making Markdown file and storing it: $TempDir$MarkdownFile\n";
	echo -e "$HugoMd" > $TempDir$MarkdownFile;
}

while true
do
	shootImage;

	read -p "Does the preview look okay? [Yn]" answerPreview
	answerPreview=${answerPreview:-"Y"};	

	case $answerPreview in
	  [Yy]* ) 
		  echo "Yes! The photo is good." ;
		  makeMarkdown "$1"; # pass the first argument to makeMarkdown 
		  kill $FehPID; 
		  break ;;
	  * ) 
		  echo "No! Reshoot the photo." ;
		  kill $FehPID;
		  answerPreview="n" ;;
	esac

done

while true
do
	read -p "Do you want to edit the post [e], post [P], or cancel [c]?" answerEdit
	answerEdit=${answerEdit:-"p"};	

	case $answerEdit in
	  [eE]* ) 
		echo "Edit the markdown file." ;
		vim $TempDir$MarkdownFile ;;
	  [pP]* )
		echo "Post the markdown and image." ;
		cp $TempDir$ImageFile $HugoPhotoDir ;
		cp $TempDir$MarkdownFile $HugoMarkdownDir ;
		cd $HugoBaseDir ;
		$HugoPostScript ;
		break ;;
	  [cC]* )
		echo "Cancel! Burn all the evidence!" ;
		rm $TempDir$ImageFile ;
		rm $TempDir$MarkdownFile ;
		break ;;
	esac

done


