' fileupdater.vbs  
' Generic VBScript to update file if input is newer than output.  
' Author Jørn-Stian Lønsetteig
' Version 2.0 - 28th of March 2009
' -----------------------------------------------------------------------------  
Option Explicit  
Dim debug,fso, objShell, outputfileObj, inputfileObj, inputfile, outputfile, localfolder

If WScript.Arguments.Named.Exists("v") Then
	debug = True
Else
	debug = False
End If

If (WScript.Arguments.Named.Exists("i") And WScript.Arguments.Named.Exists("o")) Then
	inputfile=Wscript.Arguments.Named("i")
	outputfile=Wscript.Arguments.Named("o")
	updateFile outputfile,inputfile
Else
	wscript.echo "fileupdater.vbs 2.0" & vbCrlf  _
	& "updates outputfile with inputfile, if its newer" & vbCrlf &  vbCrlf  _
	& "Input syntax must contain both /i: and /o:" & vbCrlf  _
	& "use /v for text-output" & vbCrlf  _
	& "ie: fileupdater /i:c:\master.txt /o:c:\slave.txt"
End If

 
function updateFile (output, input)
	Set objShell	= CreateObject("WScript.Shell")
	Set fso 		= CreateObject("Scripting.FileSystemObject")  
	if not fso.FileExists(input) then
	if debug then	wscript.echo "input file non-existant, exiting" end if
		wscript.quit
	end if
	If fso.FileExists(output) Then  
		set outputfileObj = fso.GetFile(output)
		set inputfileObj = fso.GetFile(input)
	if debug then	wscript.echo "output file created: " & outputfileObj.datecreated & " modified: " & outputfileObj.DateLastModified & vbCrlf _
					&"input file created: " & inputfileObj.datecreated & " modified: " & inputfileObj.DateLastModified end if
		if inputfileObj.DateLastModified > outputfileObj.DateLastModified then
			On Error Resume Next
	if debug then		wscript.echo "updating file" end if
			fso.copyFile output, Left(output,InStrRev(output,".")) & "old", true ' create backup of outputfile
			fso.copyFile input, output, true
			Wscript.Quit
		else
	if debug then		wscript.echo "input not newer than output, no update needed" end if
		end if
	Else    
		localFolder = Left(output,InStrRev(output,"\"))
	if debug then	wscript.echo "creating new file in folder " & localFolder
		On Error Resume Next
		if not fso.FolderExists(localFolder) then 'create output directory if it's not availible
	if debug then		wscript.echo "creating folder for output file" end if
			fso.CreateFolder(localFolder)
		end if
		fso.copyFile input, output, true
	End If 
	set outputfileObj = nothing
	set inputfileObj = nothing
End Function
