#=============================================================================
# mcl - The Missing CMake Library
# Copyright 2013 John Lamp
#
# Distributed under the OSI-approved Modified BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================

#!
# Usage: CheckGeneratedFiles.cmake <testName> <flagFile> <file>...
#
#  This script checks the creation time of all the <file>s listed and if any are
#  newer than the last build then <flagFile> is created. If any files cannot be
#  found then a warning is preinted and <flagFile> is created.
#
#  This is intended to be used for automatically running a test whenever any of
#  its dependencies are updated. Since files generated by add_custom_command()
#  are not CMake targets this is how we check to see if they have been updated
#  during this build.
#

set(thisFile ${CMAKE_ARGV2})
set(testName ${CMAKE_ARGV3})
set(flagFile ${CMAKE_ARGV4})

set(buildTimeFile ${testName}.lastBuild)
set(createFlag FALSE)

set(arg 5)
while(${arg} LESS ${CMAKE_ARGC})
    set(file ${CMAKE_ARGV${arg}})
    get_filename_component(file ${file} ABSOLUTE)

    if (NOT EXISTS ${file})
        message(AUTHOR_WARNING "The file '${file}' required by test "
                               "'${testName}' cannot be found.")
        set(CreateFlag TRUE)
        break()
    elseif (${file} IS_NEWER_THAN ${buildTimeFile})
        set(CreateFlag TRUE)
        break()
    endif()

    math(EXPR arg "${arg} + 1")
endwhile()

file(REMOVE ${buildTimeFile})
file(WRITE  ${buildTimeFile})

if (CreateFlag)
    file(WRITE ${flagFile})
endif()
