#!/bin/bash
#CTBrec Auto-Concatenator
#Expects 1 to be a directory, 2 to be a name, 3 to be a day (yyyy-mm-dd),
#and 4 to be a time (hh:mm:ss). In addition, it expects CTBrec to have 
#already re-encoded any VOD segments into a '.ts.mp4' file. 
#Usually done by running a 'remux/transcode' post-processing step in
#CTBrec which outputs to an mp4 file (deceptively helpful behaviour)
#Please edit SHPEAL to suit your own style.   
#-------------------------------------------------------------------------------
export TERM vt100
#set -euf
SKIP=0
OPTS="-c copy"
#Append the old output stub to a file
cat out >> out.old
#Start the new output stub w/ timestamp
echo "------$(date)------" > out
while getopts :ser:R: o
do	case "$o" in
	s) export SKIP="1"
	   echo "----RUNNING IN POST---" >> out;;
	e) export OPTS="-c:v libx264 -c:a libvorbis";;
	r) export OPTS="-c copy -vf scale=-1:${OPTARG}";;
	R) export OPTS="-c:v libx264 vf scale=-1:${OPTARG} -c:a libvorbis";;
	[?]) 
		echo "Switch not recognized" >&2
		exit 3	
	esac
done
shift $(( $OPTIND-1 ))
cd $1
#Edit this part for torrent differentiation.
SHPEAL="$2 VOD, 720p, h264, Auto-Concatenated:"
#Timestamp that the computer can read
export DATE=$(date --date="$3 $4" "+%x %X")
#The VOD timestamp, since we didn't ask for it before
export STAMP=$(date --date="$DATE" "+%Y-%m-%d_%H-%M-%S")
#Unix Epoch conversion so that we can easily do math
export EPCH=$(date --date="$DATE" "+%s")
#If there's a VOD within the last 6 hours then we want it
let 'LEPCH = EPCH-21600'
#Convert it back to date-readable timestamp
export LDATE=$(date --date="@$LEPCH" "+%x %X")
#Guess the file we're working on. This guesses pretty well.
export FILE=$(find . -name "*$2_$STAMP*.ts*" | grep -Evi '.torrent|.jpg|.png|CON')
#TOUCH TOUCH VALUE F O R  T O U C H I N G

#Sanity readout
echo "Working IN: $1" >> out
echo "Working ON: $FILE" >> out
echo -e "Stamp: $STAMP\nFrom:  $EPCH ($DATE) \nTo:    $LEPCH ($LDATE)" >> out
#If there is a ts file recording, wait to see if it gets updated
sleep 5s
#Now comes the important bit - Are we done, or are we still recording?
if [ $SKIP -eq 0 ]; then
	export CHECK=$(find -name "$2*.ts*" -newer "$FILE" | grep -Evi '.torrent|.jpg|.png')
	echo -e "Found after:\n$CHECK" >> out
fi
if [ -z "$CHECK" ];
then
	#If we don't find anything, then we are safe to go
	echo "Good" >> out
	#Time to find every VOD within the last N hours AND SORT THEM.
	#You have no idea how much pain the lack of sort caused me.
	if [ $SKIP -eq 0 ];
	then
		EXT=.ts.mp4
	else
		EXT=.ts
	fi
	find -name "$2*${EXT}*" -newermt "$LDATE" | grep -Evi '.torrent|.jpg|.png' | sort -n > files.txt
	find -name "$2*${EXT}*" -newer "$FILE" | grep -Evi '.torrent|.jpg|.png' | sort -n > not-files.txt
	comm -23 files.txt not-files.txt | sort -n > files-b.txt
	#They have ./ in front. This needs to be rectified
	sed -i -e 's/^.\///' files-b.txt
	#Get a generic enough VOD title
	export VOD="$(sed 's/_[0-9][0-9]\-[0-9][0-9]\-[0-9][0-9].*\.ts.*//g' files-b.txt | head -n 1)"
	#Add 'file' for our next step
	sed -i -e 's/^/file /' files-b.txt
	#Sanity check
	cat files-b.txt >> out
	if [ $SKIP -eq 1 ]; then
		VOD="OLD/${VOD}"
	fi
	echo "VOD Title: $VOD.mp4" >> out
	#Remove previous versions
	if [ -f $VOD.mp4.jpg ]; then
		rm $VOD.mp4.jpg >>out 2>&1
	fi
	#The BIG thing
	ffmpeg -hide_banner -stats -stats_period 5 -f concat -safe 0 -i files-b.txt ${OPTS} "$VOD".mp4 -y >>out 2>&1
	#Pack up a torrent with a message telling of its origin
	buildtorrent -q -a udp://tracker.opentrackr.org:1337/announce -c "$SHPEAL" ${VOD}.mp4 ${VOD}.mp4.torrent >>out 2>&1
	#A contact sheet for /aco/ and my own morbid curiosity
	vcs -c 8 -n 64 -H 160 "$VOD".mp4 -o "$VOD".mp4.jpg >>out 2>&1
	#Historically, I got both PNG and JPG versions. TRADITION!
	#convert "$VOD".mp4.jpg "$VOD".mp4.png >>out 2>&1
	echo "Run this command when you care: ./movtorem.sh . $2 $3 $4" >> out

	if [ $SKIP -eq 1 }; then
		export ADATE=$(date --date=@$(( $(stat -c %Y ${FILE}) + 3600 )) "+%Y%m%d%H%M")
		echo "DATE TO FIND FILE: ${ADATE}" >> out
		touch -t ${ADATE} $VOD.mp4
	fi
	FINDATE=$(date --date=@$(stat -c %Y ${VOD}.mp4) "+%Y%m%d%H%M")
	touch -t ${FINDATE} $VOD.mp4.jpg
	touch -t ${FINDATE} $VOD.mp4.torrent
	rm files.txt
	rm files-b.txt
	rm not-files.txt
	echo $VOD.mp4 >> allfiles
else
	#Don't torrent if the show isn't over!
	echo "Fuck" >> out
fi
echo "Until next time..." >> out
wall "$FILE Processing done"
exit 0
