#!/usr/bin/env bash
case "$1" in
    test)
        set -ue
        hostname
        apt-get update ; apt-get -y install libgl1-mesa-glx libegl1 libxkbcommon-x11-0 libdbus-1-3
        python3 --version
        python3 -m venv insarviz-env
        source insarviz-env/bin/activate
        pip install pdm
        pdm install --dev
        pytest
        ;;

    docs)
        # apt-get update ; apt-get -y install libgl1-mesa-glx libegl1 libxkbcommon-x11-0 libdbus-1-3
        set -ue
        # install UV
        curl -LsSf https://astral.sh/uv/0.8.0/install.sh | sh
        export PATH="$HOME/.local/bin:$PATH"

        uv venv
        uv sync # install Insarviz
        uv pip install .
        uv pip install sphinx sphinx-rtd-theme sphinxcontrib-video

        source .venv/bin/activate
        sphinx-apidoc -e -o doc -f insarviz
        ( cd doc && sphinx-build -a -b html . html )
        tar -cvzf html-doc.tar.gz -C doc/html .
        ;;

    pages)
        # refetch tags from the repository, to purge the cache
        git fetch --prune --prune-tags
        tags=( $(git tag -l 'release-*' | sort -V) )
        mkdir -p public
        (
            printf '['
            comma=
            for tag in "${tags[@]}"; do
                version="${tag#release-}"
                printf '%s{ "name": "%s", "path": "%s" }' "$comma" "$version" "$tag"
                comma=,
            done
            printf ']'
        ) > "versions.json"
        for tag in "${tags[@]}"; do
            printf "Getting docs for tag: %s\n" "$tag"
            version="${tag#release-}"
            mkdir -p "public/$tag"
            curl -sL "${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/jobs/artifacts/$tag/raw/html-doc.tar.gz?job=tag-docs" \
                | tar -xz -C "public/$tag"
            cp versions.json "public/$tag"
            latest="$tag"
        done

        mkdir -p public/staging
        tar -xzf html-doc.tar.gz -C public/staging
        cp versions.json "public/staging"

        ln -s "$latest" public/latest

        cat > public/index.html <<EOF
<!DOCTYPE html>
<html>
  <head>
    <script>window.location.replace('latest');</script>
  </head>
  <body>
  </body>
</html>
EOF
        ;;

    deploy)
        hostname
        function deploy-in() {
            set -ue

            local env="$1"; shift
            source "$env/bin/activate"
            cd /usr/contrib/cycle/insarviz/
            git fetch --tags
            git checkout "$CI_COMMIT_TAG"
            pip install .
        }
        function export-client-env() {
            declare -f deploy-in
            declare -p CI_COMMIT_TAG
        }
        ssh ist-oar "$(export-client-env) deploy-in /usr/contrib/cycle/venv-insarviz"
        ssh ist-oar "$(export-client-env) deploy-in /usr/contrib/cycle/venv_nsbas_python3"
        ;;

    *)
        printf "Error: unrecognized command '%s'\n" "$1"
        exit 1
        ;;
esac
