@echo off
::
:: Log caller ID info.
::
:: This initiates processes at both ends of a pipeline for routing caller ID
:: info from the local land line.
::
:: 1. The comtool utility captures the bytestream from a local modem and
::    writes it to the server end of the pipe.
::
:: 2. The callerIdFeed.pl process extracts caller ID info from the client end
::    of the pipe and dispatches it (write to db and send notifications)
::
::  example usage:
::
::    phonelog.cmd \\.\pipe\callerID.log
::
:: blame shardy@@differentchairs.com
::

setlocal
set LOGFILE2=
:: Optional arg can be log file name or local pipe (e.g., \\.\pipe\idlog)
if not %1.==. (
		set LOGFILE=%1
	) else (
		set LOGFILE=c:\callerID.log
	)
set MAXLOGFILESIZE=5000000
set MODEMPORTCFG=com3:9600,n,8,1
set MODEMRESET=ATZ
set MODEMSPKROFF=ATM0
set ENABLECALLERID=AT+VCID=1
set bin=%~dp0

:: (hack: handshake not right, so insert 100ms delay after outgoing bytes)
set comcmd=%bin%comtool.exe  *100 a #%MODEMPORTCFG%

:: abort if com port unavailable (presumably, I'm already running)
%comcmd% 0 >nul || goto :done

call :limitAt %MAXLOGFILESIZE% %LOGFILE% old
%comcmd% 1 ~%MODEMRESET%~ | findstr /b /e "OK"&& (
	%comcmd% 1 ~%MODEMSPKROFF%~|findstr /b /e "OK" && (
		start /min "Modem Monitor" %comcmd% L%LOGFILE% ~%ENABLECALLERID%~
		echo %logfile% | find /i "\\.\pipe\" > nul && (
			sleep 2
			title CallerID Feed
			perl.exe -n %bin%calleridfeed.pl < %logfile% | findstr "DATE TIME NMBR NAME : --- "
			)
		)
	)

:done
endlocal
goto :eof


::		=============
::		other candidate commands for enabling callerID info:
::
::		   AT#CID=1
::		   AT%CCID=1
::		   AT#CC1
::		   AT*ID1
::		   AT*IC1
::		=============


:: if filesize exceeds given size, copy to {file}.{bakExt} and delete original
:: usage - limitAt {sizeLimit} {file} {bakExt}
:limitAt
	if %3.==. goto :eof
	if not %4.==. goto :eof
	if not exist %2 goto :eof

	set maxSize=%1
	set theFile=%2
	set bakExt=%3

	set fname=%~nx2
	:: this line probably not highly backward compatible (works on xp 5.1.26)
	set currentSize=%~z2

	if  %currentSize% GEQ %maxSize% (
	  echo limiting: move %theFile% to %theFile%.%bakExt%
	  move /y %theFile% %theFile%.%bakExt%
	  )
	goto :eof