#!/bin/bash

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

make_folder () {
  rm -rf ./tmp
  mkdir ./tmp
}

install_oneget() {
    go install github.com/v8platform/oneget@latest
    export PATH=$PATH:"~/go/bin"
}

download_1c_distr() {
    oneget get --path $1 --filter platform=server64_with_all_clients platform:linux.full.x64@latest
}

find_1c_distr() {
    find $1 -name "server64*.tar.gz" -type f
}

cleanup() {
    rm -rf ./tmp
}

pushd $SCRIPT_DIR

DISTR_1C=$(find_1c_distr ./distr)

if [[ -r "$DISTR_1C" ]]
then
    echo "remove 1c distr first"
    echo $DISTR_1C
    popd
    exit 1
fi

# import
# ONEC_USERNAME
# ONEC_PASSWORD
ENV_FILE="../portal-1c.env"
if [[ -r "$ENV_FILE" ]]
then
  . $ENV_FILE
else
    echo "no env vars file"
    popd
    exit 1
fi


make_folder
download_1c_distr ./tmp
DISTR_1C=$(find_1c_distr ./tmp)

if [[ ! -r "$DISTR_1C" ]]
then
    echo "downloaded distr not found"
    popd
    exit 1
fi

mv $DISTR_1C ./distr/

cleanup

DISTR_1C=$(find_1c_distr ./distr)
echo $DISTR_1C

popd