#!/bin/bash

set -Ee

this_script_name=`basename "$0"`

on_error() {
  echo "$this_script_name:$1: error: Test FAILED"
}
trap 'on_error $LINENO' ERR

test_input_file=/tmp/nvrtc_cli_test_input.cu
test_output_file_ptx=/tmp/nvrtc_cli_test_output.ptx
test_output_file_cubin=/tmp/nvrtc_cli_test_output.cubin

cat > $test_input_file <<- EndOfMessage
template <class T>
__global__ void my_kernel(const T* in, T* out) {
  int i = blockIdx.x * blockDim.x + threadIdx.x;
  out[i] = in[i] * in[i] + T(1);
}
EndOfMessage

ptx_options="$test_input_file -o $test_output_file_ptx -lineinfo -ptx"
cubin_options="$test_input_file -o $test_output_file_cubin -lineinfo -cubin"

./nvrtc_cli $ptx_options
grep -q "Generated by NVIDIA NVVM Compiler" "$test_output_file_ptx"
grep -q "\.version" "$test_output_file_ptx"
grep -q "\.target" "$test_output_file_ptx"

./nvrtc_cli $cubin_options
file "$test_output_file_cubin" | \
    grep -q "ELF 64-bit LSB executable, NVIDIA CUDA architecture"

./nvrtc_cli $ptx_options -arch=sm_70
grep -q "\.target sm_70" "$test_output_file_ptx"

./nvrtc_cli $ptx_options -ne "my_kernel<float>" |
    grep -q "\"my_kernel<float>\" -> _Z9my_kernel"
grep -q "\.entry _Z9my_kernel" "$test_output_file_ptx"

./nvrtc_cli -h | grep -q "\-\-help"
./nvrtc_cli --help | grep -q "\-\-help"
./nvrtc_cli -V | grep -q "Cuda compilation tools, release"
./nvrtc_cli --version | grep -q "Cuda compilation tools, release"
./nvrtc_cli -arch-ls | grep -q "compute_70"
./nvrtc_cli --list-gpu-arch | grep -q "compute_70"
./nvrtc_cli -arch-ls | grep -q "(default)"
./nvrtc_cli -code-ls | grep -q "sm_70"
./nvrtc_cli --list-gpu-code | grep -q "sm_70"
./nvrtc_cli -code-ls | grep -q "(default)"
./nvrtc_cli $ptx_options -time - | grep -q ", ms"
./nvrtc_cli $ptx_options --time - | grep -q ", ms"
./nvrtc_cli $ptx_options -Lignored -L ignored --library-path ignored
cat $test_input_file | ./nvrtc_cli - | grep -q ".target"

echo "Test PASSED"
