find_package(PkgConfig REQUIRED)

list(APPEND CMAKE_PREFIX_PATH "${PETSC_DIR}/${PETSC_ARCH}")

if(PETSC_FIND_REQUIRED)
  set(_PETSC_OPTS "REQUIRED")
endif()
if(PETSC_FIND_QUIETLY)
  set(_PETSC_OPTS "QUIET")
endif()
if(PETSC_FIND_REQUIRED AND PETSC_FIND_QUIETLY)
  set(_PETSC_OPTS "REQUIRED QUIET")
endif()

pkg_check_modules(PETSC ${_PETSC_OPTS} IMPORTED_TARGET PETSc)

#TODO : set the below XXX_LIBRARIES and XXX_INCLUDE_DIRS

if(PETSC_FOUND)
   # todo modify find_packages to look for petsc dependencies when the packages are found in a petsc install instead of placing all this logic in here and relying on the PETScBuildInternal.cmake file to be available
  include(${PETSC_DIR}/${PETSC_ARCH}/lib/petsc/conf/PETScBuildInternal.cmake)
  set(PETSC_INCLUDE_DIRS "${PETSC_STATIC_INCLUDE_DIRS}")
  set(PETSC_LIBRARIES "${PETSC_STATIC_LDFLAGS}")
  if(PETSC_ZOLTAN_LIB)
    message(STATUS "Found Zoltan library as a PETSc dependency.")
    set(ZOLTAN_FOUND true)
    set(ZOLTAN_LIBRARIES ${PETSC_ZOLTAN_LIB})
    set(ZOLTAN_INCLUDE_DIRS )
  endif()
  if(PETSC_PARMETIS_LIB)
    message(STATUS "Found Metis/Parmetis library as PETSc dependency.")
    set(PARMETIS_FOUND true)
    set(METIS_FOUND true)
    set(PARMETIS_LIBRARIES ${PETSC_PARMETIS_LIB} ${PETSC_METIS_LIB})
    set(METIS_LIBRARIES ${PETSC_METIS_LIB})
    set(PARMETIS_INCLUDE_DIRS )
    set(METIS_INCLUDE_DIRS )
  endif()
  if(PETSC_HDF5_LIB)
    message(STATUS "Found HDF5 library as PETSc dependency.")
    set(HDF5_FOUND true)
    set(HDF5_LIBRARIES ${PETSC_NDF5HL_FORTRAN_LIB} ${PETSC_HDF5_FORTRAN_LIB} ${PETSC_HDF5_HL_LIB} ${PETSC_HDF5_LIB})
    set(HDF5_INCLUDE_DIRS ${PETSC_STATIC_INCLUDE_DIRS})
  endif()
endif(PETSC_FOUND)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(PETSC DEFAULT_MSG PETSC_LIBRARIES PETSC_INCLUDE_DIRS)
mark_as_advanced(PETSC_LIBRARIES PETSC_INCLUDE_DIRS)
