1#!/usr/bin/env bash
2#
3# Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
4#
5# SPDX-License-Identifier: BSD-2-Clause
6#
7
8#
9# Execute a command that generates a single output file. If the output file is
10# has unchanged contents, restore the old modification date to prevent GNU make
11# et. al. from continuing building down the dependency chain.
12#
13
14if [ $# -le 1 ]; then
15    echo "Usage: $0 <output file> <cmd> [<cmd args> ...]"
16    exit 1
17fi
18
19# Get the target file
20TARGET_FILE=$1
21shift
22
23# If the file doesn't exist, we always run the command.
24if [ ! -e $TARGET_FILE ]; then
25    V=$@
26    sh -c "$V"
27    exit $?
28fi
29
30# Make a copy
31TMP_FILE=`mktemp /tmp/XXXXXXXX`
32cp -a $TARGET_FILE $TMP_FILE
33
34# Run the command
35V=$@
36sh -c "$V"
37ERROR_CODE=$?
38
39# Restore the old file if the contents are the same.
40if cmp $TMP_FILE $TARGET_FILE > /dev/null 2> /dev/null; then
41    mv -f $TMP_FILE $TARGET_FILE
42else
43    rm -f $TMP_FILE
44fi
45
46# Return with the error code.
47exit $ERROR_CODE
48
49