#!/bin/bash
set -e

SERVICE_NAME=$1

if [[ "$bamboo_planRepository_branchName" == "master" ]]
then
    branchVersion=$(cat version.yaml | grep -Eo "version: .*" | sed -s 's|version: \(.*\)\..*\..*|\1|g')
    latestVersion=$( semver $(git tag -l "${branchVersion}.*" ) | tail -n1 )
    newVersion="$(semver $latestVersion -p -i minor)"
    echo "new release on master with version $newVersion"
elif [[ "$bamboo_planRepository_branchName" == release* ]]
then
    branchVersion=$(echo $bamboo_planRepository_branchName | sed -s 's|release\/\([0-9]\+\.[0-9]\+\)\.x|\1|')
    latestVersion=$( semver $(git tag -l "${branchVersion}.*" ) | tail -n1 )
    newVersion="$(semver $latestVersion -p -i patch)"
    echo "new release on $bamboo_planRepository_branchName with version $newVersion"
elif [[ "${bamboo_version_tag}" != "dev" ]]
then
    newVersion="${bamboo_version_tag}"
    echo "new special version bild with $newVersion"
else
    newVersion="${bamboo_planRepository_1_branch}_${bamboo_buildNumber}"
    echo "gitTag=${newVersion}" > git.tag
    echo "dev build with tag ${newVersion}"
    python3 -m venv build_venv
    source build_venv/bin/activate
    python3 -m pip install --upgrade pip

    pip install dvc
    pip install 'dvc[ssh]'
    dvc pull

    echo "index-url = https://${bamboo_nexus_user}:${bamboo_nexus_password}@nexus.iqser.com/repository/python-combind/simple" >> pip.conf
    echo "${bamboo_nexus_password}" | docker login --username "${bamboo_nexus_user}" --password-stdin nexus.iqser.com:5001
    docker build -f Dockerfile .
    exit 0
fi

echo "gitTag=${newVersion}" > git.tag

python3 -m venv build_venv
source build_venv/bin/activate
python3 -m pip install --upgrade pip

pip install dvc
pip install 'dvc[ssh]'
dvc pull

echo "index-url = https://${bamboo_nexus_user}:${bamboo_nexus_password}@nexus.iqser.com/repository/python-combind/simple" >> pip.conf
docker build -f Dockerfile  -t nexus.iqser.com:5001/red/$SERVICE_NAME:${newVersion} .
echo "${bamboo_nexus_password}" | docker login --username "${bamboo_nexus_user}" --password-stdin nexus.iqser.com:5001
docker push nexus.iqser.com:5001/red/$SERVICE_NAME:${newVersion}
