#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2006-2025 Knut Reinert & Freie Universität Berlin
# SPDX-FileCopyrightText: 2016-2025 Knut Reinert & MPI für molekulare Genetik
# SPDX-License-Identifier: BSD-3-Clause

set -Eeuo pipefail

WORKDIR=${TMPDIR:-/tmp}/seqan3-amalgamate-sdsl
mkdir -p "${WORKDIR}"
cd "${WORKDIR}"

SDSL_PATH="${WORKDIR}/sdsl-lite/"
SDSL_ARCHIVE_URL="https://github.com/xxsds/sdsl-lite/archive/refs/heads/master.tar.gz"

CPP_AMALGAMATE_BINARY_URL="https://github.com/Felerius/cpp-amalgamate/releases/download/1.0.1/cpp-amalgamate-x86_64-unknown-linux-gnu"

CXX=${CXX:-c++}
CPP_AMALGAMATE=cpp-amalgamate

if [[ ! -d "${SDSL_PATH}" || ! -f "${SDSL_PATH}"/include/sdsl/version.hpp ]]; then
    mkdir -p "${SDSL_PATH}"
    wget --quiet --output-document=/dev/stdout "${SDSL_ARCHIVE_URL}" | tar -xz -C "${SDSL_PATH}" --strip-components=1
fi

if ! command -v "${CPP_AMALGAMATE}" &> /dev/null; then
    if [[ ! -f cpp-amalgamate ]]; then
        wget --quiet --output-document=cpp-amalgamate "${CPP_AMALGAMATE_BINARY_URL}"
    fi

    chmod +x cpp-amalgamate
    CPP_AMALGAMATE=${WORKDIR}/cpp-amalgamate
fi

cat <<EOL > includes.cpp
#include <sdsl/bit_vectors.hpp>
#include <sdsl/int_vector.hpp>
#include <sdsl/suffix_arrays.hpp>
#include <sdsl/suffix_trees.hpp>
EOL

"${CPP_AMALGAMATE}" --quiet --dir "${SDSL_PATH}/include" --cyclic-include warn --output amalgamated.hpp includes.cpp
grep -v "#include <sdsl/" amalgamated.hpp > decycled.hpp

# This command strips all comments.
CONTENT=$(${CXX} -fpreprocessed -dD -E -P -w decycled.hpp)

# Parameter expansion/replace: ${variable//search/replace}. https://www.shellcheck.net/wiki/SC2001
CONTENT=${CONTENT//SDSL_/SDSL3_}
CONTENT=${CONTENT//namespace sdsl/namespace seqan3::contrib::sdsl}
CONTENT=${CONTENT//sdsl::/seqan3::contrib::sdsl::}

## Patches
# [C++26] `std::is_trivial` is deprecated: use `is_trivially_default_constructible && is_trivially_copyable` instead
CONTENT=${CONTENT//std::is_trivial<X>::value/std::is_trivially_default_constructible<X>::value \&\& std::is_trivially_copyable<X>::value}

cat <<EOL > sdsl-lite.hpp
// SPDX-FileCopyrightText: 2016 SDSL Project Authors
// SPDX-License-Identifier: BSD-3-Clause

// This file was generated by https://github.com/seqan/seqan3/blob/main/test/scripts/amalgamate-sdsl.sh
//
// Including this file is equivalent to including sdsl/{bit_vectors,int_vector,suffix_arrays,suffix_trees}.hpp.
// This is also called an amalgamated header: a single, self-contained header file.
//
// Additionally:
// * All comments were removed.
// * "SDSL_" was replaced with "SDSL3_". This affects macros and include guards.
// * The namespace was changed from "sdsl" to "seqan3::contrib::sdsl".
// * "std::is_trivial" was replaced with "is_trivially_default_constructible && is_trivially_copyable".

#pragma once

// clang-format off
${CONTENT}
// clang-format on

EOL

rm includes.cpp amalgamated.hpp decycled.hpp

echo "${WORKDIR}"/sdsl-lite.hpp
