#!/bin/bash
set -e
if [ $# -eq 0 ]; then
    install=false
else
    if [ "$1" = "install" ]; then
        install=true
    else
        echo "Invalid command, supported commands are: 'install'"
        exit 1
    fi
fi

case "$(uname -s)" in
Linux)
    . /etc/os-release
    OS="${NAME// /}"
    case "$OS" in
    Ubuntu|Debian|LinuxMint)
        deps=(qemu-utils python3-dev libssl-dev libev-dev libvirt-dev libffi-dev libyaml-dev pipx build-essential jq curl)
        has_pkg="dpkg -s"
        install_pkg="sudo apt-get -q install -y"
        export DEBIAN_FRONTEND=noninteractive
        ;;
    RedHatEnterpriseWorkstation|RedHatEnterpriseServer|RedHatEnterprise|CentOS|CentOSStream|AlmaLinux|RockyLinux|Fedora|FedoraLinux)
        # Use the newest version we find
        if [ -z "$PYTHON" ]; then
            for i in 13 12 11 10; do
                command -v "python3.$i" > /dev/null && PYTHON="python3.$i" && break
            done
        fi
        if [ -z "$PYTHON" ]; then
            # This would be bizarre, but I suppose possible
            PYTHON=${PYTHON:-"python3"}
        fi
        # rpm/dnf is the default, to reduce repetition in the case statement
        has_pkg="rpm -q --whatprovides"
        install_pkg="sudo dnf install -y"
        deps=(libev-devel libffi-devel libvirt-devel "$PYTHON-devel" pipx)
        ;;
    "openSUSE project"|"SUSE LINUX"|"openSUSE"|"openSUSELeap"|"openSUSETumbleweed")
        PYTHON=${PYTHON:-"python3"}
        deps=("$PYTHON" "$PYTHON-devel" "$PYTHON-pipx" libev-devel libffi-devel libvirt-devel)
        has_pkg="rpm -q --whatprovides"
        install_pkg="sudo zypper install -y"
        ;;
    esac
    ;;

Darwin)
    deps=(python libvirt libev libffi pipx uv)
    has_pkg="brew list"
    install_pkg="brew install"
    ;;
esac
for package in "${deps[@]}"; do
    if ! $has_pkg "$package" &>/dev/null; then
        # add a space after old values
        missing="${missing:+$missing }$package"
    fi
done
if [ -n "$missing" ]; then
    echo "$0: missing required packages:" 1>&2
    echo "$missing"
    if [ "$install" = true ]; then
        echo "Installing missing packages..."
        $install_pkg $missing
    else
        echo "Please install missing packages or run './bootstrap install'"
        echo "$install_pkg $missing"
        exit 1
    fi
fi

# Attempt to force a UTF-8 locale without forcing English
LANG=${LANG:=C}
LC_ALL=${LC_ALL:=C}
export LANG="${LANG/.*/}.utf-8"
export LC_ALL="${LC_ALL/.*/}.utf-8"

[ -z "$NO_CLOBBER" ] && rm -rf virtualenv
command -v uv > /dev/null || pipx install --quiet uv
command -v uv > /dev/null || pipx ensurepath --quiet
PATH=$PATH:$HOME/.local/bin
# Create the venv if it does not exist, and install teuthology and dependencies
uv sync --quiet --frozen --all-extras
# To avoid crashing older dispatchers
ln -sf .venv virtualenv

# Install ansible collections
uv run ansible-galaxy install -r requirements.yml
