set (ARGTABLE3_TAG "release-v3.2.1.7704006")
set (ARGTABLE3_GITHUB_ARCHIVE_HASH "SHA256=53d74e734cfed36bd36f067ceb5d38ddb6679cfc7ae0b917c50631fb2018af9b")
set (ARGTABLE3_BITBUCKET_ARCHIVE_HASH "SHA256=3983f04f68818bb0d60ed2def1cdeb7a04fa0c69ecca0ccefc76dbebab202bc0")
set (ARGTABLE3_GITLAB_ARCHIVE_HASH "SHA256=53d74e734cfed36bd36f067ceb5d38ddb6679cfc7ae0b917c50631fb2018af9b")

function (cmake_fetch_argtable3 FALLBACK FETCH_MODE)
  if (DEFINED CMAKE_ARGTABLE3_POPULATED)
    return ()
  endif ()

  include (FetchContent)
  set (FETCHCONTENT_QUIET OFF)

  if (EXISTS "${PROJECT_SOURCE_DIR}/argtable3/src")
    set (argtable3_POPULATED true)
    set (argtable3_SOURCE_DIR "${PROJECT_SOURCE_DIR}/argtable3")
  elseif (FALLBACK STREQUAL "github")
    set (
      ARGTABLE3_FETCH_OPTIONS
      GIT_REPOSITORY "https://github.com/andrew-aladev/argtable3.git"
      GIT_TAG ${ARGTABLE3_TAG}
    )
  elseif (FALLBACK STREQUAL "github-archive")
    set (
      ARGTABLE3_FETCH_OPTIONS
      URL "https://github.com/andrew-aladev/argtable3/archive/refs/tags/${ARGTABLE3_TAG}.tar.gz"
      URL_HASH ${ARGTABLE3_GITHUB_ARCHIVE_HASH}
    )
  elseif (FALLBACK STREQUAL "bitbucket")
    set (
      ARGTABLE3_FETCH_OPTIONS
      GIT_REPOSITORY "https://bitbucket.org/andrew-aladev/argtable3.git"
      GIT_TAG ${ARGTABLE3_TAG}
    )
  elseif (FALLBACK STREQUAL "bitbucket-archive")
    set (
      ARGTABLE3_FETCH_OPTIONS
      URL "https://bitbucket.org/andrew-aladev/argtable3/get/${ARGTABLE3_TAG}.tar.gz"
      URL_HASH ${ARGTABLE3_BITBUCKET_ARCHIVE_HASH}
    )
  elseif (FALLBACK STREQUAL "gitlab")
    set (
      ARGTABLE3_FETCH_OPTIONS
      GIT_REPOSITORY "https://gitlab.com/andrew-aladev/argtable3.git"
      GIT_TAG ${ARGTABLE3_TAG}
    )
  elseif (FALLBACK STREQUAL "gitlab-archive")
    set (
      ARGTABLE3_FETCH_OPTIONS
      URL "https://gitlab.com/andrew-aladev/argtable3/-/archive/${ARGTABLE3_TAG}/argtable3-${ARGTABLE3_TAG}.tar.gz"
      URL_HASH ${ARGTABLE3_GITLAB_ARCHIVE_HASH}
    )
  else ()
    message (FATAL_ERROR "Invalid argtable3 fallback: ${FALLBACK}")
  endif ()

  if (DEFINED ARGTABLE3_FETCH_OPTIONS)
    FetchContent_Declare (argtable3 ${ARGTABLE3_FETCH_OPTIONS})
    FetchContent_GetProperties (argtable3)
    if (NOT argtable3_POPULATED)
      FetchContent_Populate (argtable3)
    endif ()
  endif ()

  set (
    CMAKE_ARGTABLE3_POPULATED ${argtable3_POPULATED}
    CACHE BOOL "argtable3 populated"
  )
  set (
    CMAKE_ARGTABLE3_SOURCE_DIR ${argtable3_SOURCE_DIR}
    CACHE STRING "argtable3 source dir"
  )

  mark_as_advanced (
    CMAKE_ARGTABLE3_POPULATED
    CMAKE_ARGTABLE3_SOURCE_DIR
  )

  if (NOT CMAKE_ARGTABLE3_POPULATED AND FETCH_MODE STREQUAL "REQUIRED")
    message (FATAL_ERROR "argtable3 is required")
  endif ()
endfunction ()
