#!/bin/sh -e

prefix=/usr/local
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir_pkg=${prefix}/include/neko
FC=mpif90
FCFLAGS='-Wl,-rpath=/usr/local/lib/gcc12  -I/usr/local/include'

# Setup accelerator backend
HAVE_CUDA_BCKND=0
if [ $HAVE_CUDA_BCKND -eq 1 ]; then
    NVCC=
    CUDA_CFLAGS=''
    CUDA_ARCH=''
fi

HAVE_HIP_BCKND=0
if [ $HAVE_HIP_BCKND -eq 1 ]; then
    HIPCC=
    HIP_HIPCC_FLAGS=''
fi

printf "\n%s\n" 'N E K O build tool, Version 1.1.2'
printf "%s\n" '(build: 2026-11-15 on x86_64-portbld-dragonfly6.4 using gnu)'

# Ensure user provides at least one .f90 file
if [ $# -eq 0 ]; then
    if [ $HAVE_CUDA_BCKND -eq 1 ]; then
        echo "Usage: makeneko <file1.f90> <file2.f90> <file3.cu>"
    elif [ $HAVE_HIP_BCKND -eq 1 ]; then
        echo "Usage: makeneko <file1.f90> <file2.f90> <file3.hip>"
    else
        echo "Usage: makeneko <file1.f90> <file2.f90>"
    fi
    exit 1
fi

echo "Building user NEKO ..."

# Remove usr_driver.f90 if it exists. Can cause compilation errors otherwise
if [ -f usr_driver.f90 ]; then
    rm usr_driver.f90
fi


# Collect user-provided .f90, .cu and .hip files
USER_FILES=""
USER_BCKND_FILES=""
for file in "$@"; do
    case "$file" in
        *.f90|*.F90) USER_FILES="$USER_FILES $file" ;;
        *)
            if [ $HAVE_CUDA_BCKND -eq 1 ]; then
                case "$file" in
                    *.cu) USER_BCKND_FILES="$USER_BCKND_FILES $file" ;;
                    *) echo "Warning: Ignoring non-Fortran file '$file'" ;;
                esac
            elif [ $HAVE_HIP_BCKND -eq 1 ]; then
                case "$file" in
                    *.hip) USER_BCKND_FILES="$USER_BCKND_FILES $file" ;;
                    *) echo "Warning: Ignoring non-Fortran file '$file'" ;;
                esac
            else
                echo "Warning: Ignoring non-Fortran file '$file'"
            fi
            ;;
    esac
done

if [ -z "$USER_FILES" ]; then
    echo "ERROR: No valid .f90 files provided. Please specify at least one Fortran source file."
    exit 2
fi

# Check if we have `module user` in one of the .f90 files
HAS_USER_MODULE=0
USER_MODULE_FILE=""
for file in $USER_FILES; do
    if /usr/bin/grep -qi '^[[:space:]]*module[[:space:]]\+user' "$file"; then
        HAS_USER_MODULE=1
        USER_MODULE_FILE="$file"
        break
    fi
done

if [ $HAS_USER_MODULE -eq 1 ]; then
  echo "Detected the module named 'user' in" $USER_MODULE_FILE
else
  echo "No module named 'user' detected."
fi


# Extract module names from user-provided .f90 files.
# This excludes the `module user`, since it is special.
USER_MODULES=$(/usr/bin/grep -hE '^[[:space:]]*module[[:space:]]+[a-zA-Z_][a-zA-Z0-9_]*' $USER_FILES 2>/dev/null | \
               /usr/bin/grep -vE '^[[:space:]]*!' | \
               /usr/bin/grep -vE 'module procedure|module[[:space:]]+user' | \
               /usr/bin/awk  '{print $2}' | sort -u)

if [ -n "$USER_MODULES" ]; then
  echo "Detected the following custom modules:"
  for mod in $USER_MODULES; do
    echo "    -" $mod
  done
else
  echo "No custom modules detected."
fi

# Extract those that register types
TYPEINJECTING_MODULES=""
for mod in $USER_MODULES; do
  f90file=$(echo $USER_FILES | tr ' ' '\n' | /usr/bin/grep -i "${mod}\.f90$")
  if /usr/bin/grep -iq "subroutine[[:space:]]\+${mod}_register_types" "$f90file"; then
    TYPEINJECTING_MODULES="$TYPEINJECTING_MODULES $mod"
  fi
done

if [ -n "$TYPEINJECTING_MODULES" ]; then
  echo "The following custom modules register types:"
  for mod in $TYPEINJECTING_MODULES; do
    echo "    -" $mod
  done
else
  echo "No custom modules register types."
fi

# No user module and no types injection --- no need for makeneko!
if [ $HAS_USER_MODULE -eq 0 ] && [ -z "$TYPEINJECTING_MODULES" ]; then
    echo "ERROR: No 'user' module detected and no modules that inject custom types found."
    echo "       There is no need for a user neko in this case, just use the default neko executable!"
    exit 2
fi

# Create usr_driver.f90
cat > usr_driver.f90 << _ACEOF
program usrneko
  use neko
_ACEOF

if [ $HAS_USER_MODULE -eq 1 ]; then
  echo "  use user" >> usr_driver.f90
fi

# Insert `use` statements for local user .f90 files
for mod in $USER_MODULES; do
  echo "  use $mod" >> usr_driver.f90
done

cat >> usr_driver.f90 << _ACEOF

  type(case_t), target :: C

  ! Register all user-defined types
_ACEOF

if [ $HAS_USER_MODULE -eq 1 ]; then
  echo "  call user_setup(C%user)" >> usr_driver.f90
fi


# Register types from local user .f90 files
if [ $HAS_USER_MODULE -eq 1 ] && [ -n "$TYPEINJECTING_MODULES" ]; then
  echo "  if (C%user%suppress_type_injection .eqv. .false.) then " >> usr_driver.f90
  for mod in $TYPEINJECTING_MODULES; do
    echo "     call ${mod}_register_types()" >> usr_driver.f90
  done
  echo "  end if" >> usr_driver.f90
else
  for mod in $TYPEINJECTING_MODULES; do
    echo "  call ${mod}_register_types()" >> usr_driver.f90
  done
fi

cat >> usr_driver.f90 << _ACEOF
  call neko_init(C)
  call neko_user_access%init(C)
  call neko_solve(C)
  call neko_finalize(C)

end program usrneko
_ACEOF

# Compile backend files
USER_BCKND_OBJ=''
if [ ! -z "$USER_BCKND_FILES" ]; then
    for file in $USER_BCKND_FILES; do
        if [ $HAVE_CUDA_BCKND -eq 1 ]; then
            $NVCC -c $CUDA_ARCH $CUDA_CFLAGS -I$includedir_pkg -I./ "$file" -o "${file%.cu}.o"
            USER_BCKND_OBJ="$USER_BCKND_OBJ ${file%.cu}.o"
        elif [ $HAVE_HIP_BCKND -eq 1 ]; then
            $HIPCC -c $HIP_HIPCC_FLAGS -I$includedir_pkg -I./ "$file" -o "${file%.hip}.o"
            USER_BCKND_OBJ="$USER_BCKND_OBJ ${file%.hip}.o"
        fi
    done
fi

# Compile everything
$FC $FCFLAGS -I$includedir_pkg -L$libdir $USER_FILES $USER_BCKND_OBJ usr_driver.f90 -lneko  -Wl,-rpath=/usr/local/lib/gcc12  -L/usr/local/lib/gcc12 -fno-lto  -L/usr/local/lib -ljsonfortran   -lopenblas    -o neko

rm -f usr_driver.f90
printf "%s\n" ' Done!'
