#!/usr/bin/env bash
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# Wrapper script for fwupbuild.
#
# This script is intended to be called from the repository root directory, e.g.
# $ ./fwupbuild init
# $ ./fwupbuild build
#
# Once set up it will detect a virtual env and activate it if found, passing
# through the various values to the python implementation.
#

# Resolve symlinks so SCRIPT_DIR is always the repo root,
# even when invoked via venv/bin/fwupbuild -> ../../fwupbuild
SCRIPT_DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"

# A marker file placed by fwupbuild init so we know it's our directory
MARKER_FILE="this-is-a-fwupd-build-root"

# This is a bit annoying but it is supposed to work without the
# venv activate script...
#
# Check for -C <directory> in the arguments so we can use the right python.
# The -C flag is consumed by the python side, we just peek at it here.
C_DIR=""
for ((i = 1; i <= $#; i++)); do
    arg="${!i}"
    if [[ "$arg" = "-C" ]]; then
        next=$((i + 1))
        C_DIR="${!next}"
        break
    fi
done

# VIRTUAL_ENV is set by <venv>/bin/activate, use that or otherwise
# search for the directory most recently created by our init.
# A -C flag takes precedence over both.
if [[ -n "${C_DIR}" ]]; then
    VENV="${C_DIR}"
    if [[ -n "${VIRTUAL_ENV}" ]] && [[ "$(realpath "${VIRTUAL_ENV}")" != "$(realpath "${C_DIR}")" ]]; then
        echo "${C_DIR} must match current virtualenv, run 'deactivate' to drop the virtualenv"
        exit 1
    fi
    source "${VENV}/bin/activate"
elif [[ -n "${VIRTUAL_ENV}" ]]; then
    VENV="${VIRTUAL_ENV}"
else
    # Find the most recent stamped venv
    latest_marker=""
    while IFS= read -r -d '' marker; do
        if [[ -z "${latest_marker}" ]] || [[ "${marker}" -nt "${latest_marker}" ]]; then
            latest_marker="${marker}"
        fi
    done < <(find ./ -type f -name "${MARKER_FILE}" -print0)
    if [[ -n "${latest_marker}" ]]; then
        VENV="$(dirname "${latest_marker}")"
    fi
fi

if [[ -e "${VENV}/bin/activate" ]]; then
    if [[ -z "$VIRTUAL_ENV" ]]; then
        source "${VENV}/bin/activate"
    fi
    PYTHON="${VENV}/bin/python3"
elif [[ -n "${VENV}" ]] && [[ -f "${VENV}/bin/python3" ]]; then
    PYTHON="${VENV}/bin/python3"
    export PATH="${VENV}/bin:${PATH}"
else
    PYTHON=python3
fi

exec "${PYTHON}" "${SCRIPT_DIR}/contrib/fwupbuild/__main__.py" "$@"
