#!/usr/bin/env fslpython
#
# Call an appropriate variant of eddy based on
# what is installed, and whether we have a GPU.


import               sys
import               os
import os.path    as op
import subprocess as sp


def main():
    """Call an appropriate variant of eddy based on what is installed, and
    whether a CUDA driver is available.
    """
    fsldir    = os.environ['FSLDIR']
    find_cuda = op.join(fsldir, 'bin', 'find_cuda_exe')
    eddy_cuda = sp.check_output((find_cuda, 'eddy_cuda'), text=True).strip()
    eddy_cpu  = op.join(fsldir, 'bin', 'eddy_cpu')

    # Call eddy_cuda if it exists and we
    # are running on a system with a GPU
    if eddy_cuda != '':
        cmd = eddy_cuda

    # Otherwise fall back to eddy_cpu
    elif op.exists(eddy_cpu):
        cmd = eddy_cpu

    else:
        print(f'Cannot find suitable eddy executable in {fsldir}/bin/!')
        sys.exit(1)

    os.execl(cmd, cmd, *sys.argv[1:])


if __name__ == '__main__':
    main()
