#!/bin/sh
# Copyright 2023 Huawei Cloud Computing Technology Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

readonly ROOT="$(pwd)"
readonly LBRDIR="${TMPDIR}/local-build-root"
readonly OUT="${TMPDIR}/out"
readonly JUST="${ROOT}/bin/tool-under-test"
readonly LOCAL_TOOLS="${TMPDIR}/tools"

mkdir -p "${LOCAL_TOOLS}"
cat > "${LOCAL_TOOLS}/flaky" <<'EOF'
echo Will fail to create files, but exit 0
exit 0
EOF
chmod 755 "${LOCAL_TOOLS}/flaky"

touch ROOT
cat > TARGETS <<EOF
{ "":
  { "type": "generic"
  , "outs": ["a.txt", "b.txt"]
  , "cmds": ["${LOCAL_TOOLS}/flaky"]
  }
}
EOF
cat TARGETS
echo

echo
echo Local Testing
echo

# The build should fail, as the requested outputs are not generated by the
# flaky tool
"${JUST}" build --local-build-root "${LBRDIR}" 2>&1 && exit 1 || :

cat > "${LOCAL_TOOLS}/flaky" <<'EOF'
echo This time will also create the files
echo Hello > a.txt
echo World > b.txt
exit 0
EOF

# Retrying should succeed, as semantically failed actions should not
# be used from cache.
mkdir -p "${OUT}"
"${JUST}" install --local-build-root "${LBRDIR}" -o "${OUT}" 2>&1
grep Hello "${OUT}/a.txt"
grep World "${OUT}/b.txt"

echo
echo Remote Testing
echo
REMOTE_ARGS="--local-build-root ${LBRDIR} -r ${REMOTE_EXECUTION_ADDRESS}"
if [ -n "${COMPATIBLE:-}" ]
then
    REMOTE_ARGS="${REMOTE_ARGS} --compatible"
fi

cat > "${LOCAL_TOOLS}/flaky" <<'EOF'
echo Will fail to create files, but exit 0
exit 0
EOF


"${JUST}" build ${REMOTE_ARGS} 2>&1 && exit 1 || :

cat > "${LOCAL_TOOLS}/flaky" <<'EOF'
echo This time will also create the files
echo Hello > a.txt
echo World > b.txt
exit 0
EOF

rm -rf "${OUT}"
mkdir -p "${OUT}"
"${JUST}" install ${REMOTE_ARGS} -o "${OUT}" 2>&1
grep Hello "${OUT}/a.txt"
grep World "${OUT}/b.txt"

echo OK
