#!/bin/bash

set -euo pipefail

# Checking that we got all arguments
if [[ $# -ne 3 ]]; then
    echo "Illegal number of arguments: $#. Expected: 3"
    exit 1
fi

DEVP_BIN=$1
PROTOC_VERSION=$2
OS_VERSION=$3

if [ "${OS_VERSION}" = "Windows_NT" ]
then
	echo "Unsupported OS ${OS_VERSION}"
	exit 1
fi

# Preparing protoc zip file name
UNAME_S=$(uname -s)
if [ "Linux" = "${UNAME_S}" ];
then
	OSNAME="linux"
elif [ "Darwin" = "${UNAME_S}" ];
then
	OSNAME="osx"
else
	echo "Unsupported OS ${UNAME_S}"
	exit 1
fi

UNAME_M=$(uname -m)
if [ "x86_64" = "${UNAME_M}" ] || [ "arm64" = "${UNAME_M}" ];
then
	PROTOC_ARCH="${OSNAME}-x86_64"
else
	PROTOC_ARCH="${OSNAME}-x86_32"
fi

PROTOC_ZIP_NAME="protoc-${PROTOC_VERSION}-${PROTOC_ARCH}.zip"
PROTOC_URL="https://nexus.mws-team.ru/repository/github.com/google/protobuf/releases/download/v${PROTOC_VERSION}/${PROTOC_ZIP_NAME}"
PROTOC_DIR="${DEVP_BIN}/protoc"
PROTOC_ZIP_PATH="${PROTOC_DIR}/${PROTOC_ZIP_NAME}"

mkdir "${PROTOC_DIR}"

curl -sSLO --output-dir "${PROTOC_DIR}" "${PROTOC_URL}"
unzip -qq "${PROTOC_ZIP_PATH}" -d "${PROTOC_DIR}"
rm "${PROTOC_ZIP_PATH}"
