#!/usr/bin/env bash
#
#bamboo remote agent imaging ci running script

echo "$0 $@"
set -euxo pipefail

git_hash="$1"
zimbot_name="$2"
calibration_branch="$3"
# Replace commas with spaces since zimage expects host names to be separated by spaces
limit_hosts_imaging="${4/,/ }"

bamboo_root="$HOME/bamboo"

function run_playbook() {
    cd "$bamboo_root/driving/imaging/zimage" && \
    export VAULT_COBBLER_PASSWORD="$bamboo_vault_cobbler_password" && \
    ./run_playbook.py imaging_server_os IS.1 --live -- --skip-tags write_imaging_source_checksums_file && \
    ./run_playbook.py imaging_server_customization IS.1 --live
}

function run_zimage() {
    echo "Deploying OS image of ci git hash $git_hash to $zimbot_name"
    #force to use zimage installed by run_playbook on system
    PYTHONPATH="" zimage sync --all "$zimbot_name" ${limit_hosts_imaging:+$limit_hosts_imaging}

    PYTHONPATH="" zimage image "$zimbot_name" ${limit_hosts_imaging:+$limit_hosts_imaging} --ci_build
}

function run_zstart() {
    echo "Running zstart on $zimbot_name ai machine"
    # Clear PYTHONPATH so that zimage will use the system zimage python package
    # --no-update so that we test the version of zstart in the images
    PYTHONPATH="" zimage deploy "$zimbot_name" --zstart="$git_hash --no-update --local --no-drive --no-imageries --no-models --kraken --calibration $calibration_branch"
}
run_playbook

run_zimage

run_zstart
