#!/bin/bash
glibc_version=$(ldd --version | head -n1 | grep -oE '[0-9]+\.[0-9]+' | head -n1)

index_url="https://pypi.loongnix.cn/loongson/pypi/+simple"
trusted_host="pypi.loongnix.cn"

version_compare_ge() {
    awk -v v1="$1" -v v2="$2" 'BEGIN {
        split(v1, a, ".");
        split(v2, b, ".");
        if (a[1] > b[1] || (a[1] == b[1] && a[2] >= b[2])) exit 0;
        exit 1;
    }'
}

version_compare_eq() {
    [[ "$1" == "$2" ]]
}

if version_compare_ge "$glibc_version" "2.38"; then
    index_url="https://lpypi.loongnix.cn/loongson/pypi/+simple"
    trusted_host="lpypi.loongnix.cn"
elif ! version_compare_eq "$glibc_version" "2.28"; then
    echo "Error: there is no supported supplemental PyPI mirror for glibc version $glibc_version." >&2
    exit 1
fi

pip_conf_content=$(cat <<EOF
[global]
timeout = 60
index-url = $index_url
extra-index-url = https://pypi.tuna.tsinghua.edu.cn/simple

[install]
trusted-host = 
    $trusted_host
    pypi.tuna.tsinghua.edu.cn
EOF
)

is_global=false
for arg in "$@"; do
    case "$arg" in
        -g|--global|g|global)
            is_global=true
            ;;
    esac
done

if $is_global; then
    if [ "$(id -u)" -eq 0 ]; then
        echo "$pip_conf_content" > /etc/pip.conf
	echo "Global pip config written to /etc/pip.conf"
    else
	echo "Trying to write global config using sudo"
	echo "$pip_conf_content" | sudo tee /etc/pip.conf > /dev/null && \
	    echo "Global pip config written to /etc/pip.conf" || \
	    echo "Failed to write global config, check sudo permission"
    fi
else
    mkdir -p ~/.pip
    echo "$pip_conf_content" > ~/.pip/pip.conf
    echo "User pip config written to ~/.pip/pip.conf"
fi

pip3 install -U pip
