#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

[ "$CCI_SRC" ] || export CCI_SRC=/c/cbs
[ "$LKP_SRC" ] || export LKP_SRC=/c/lkp-tests

. $CCI_SRC/container/defconfig.sh

backup_repo()
{
	local repo=$1
	local git_branch=$2

        timestamp=$(date "+%Y%m%d%H%M%s")

        cd /c
        [ -d "./$repo" ] && mv $repo $repo-$timestamp
        download_repo "$repo" "$git_branch"
}

install_lkp_tests()
{
        cd $LKP_SRC
        make install
}

upgrade_service()
{
	export deploy_k8s=true

	kubectl create -f $CCI_SRC/container/ -n development >/dev/null 2>&1

	cd $CCI_SRC/sparrow || return
	k8s/generate-config
	k8s/generate-secrets
	4-docker/buildall
	k8s/pack-lkp

	find $CCI_SRC/sbin/ -name "es-*-mapping.sh" -exec sh {} \;
}

pack_lkp()
{
        lkp_tag=$(git -C $LKP_SRC describe --abbrev=0 --tags)
        echo "y/n" | sh $CCI_SRC/container/lkp-initrd/run $lkp_tag

        load_pack_vars
        [ "$remote_lkp_pack_server" ] && {
                rsync -ra /c/lkp-tests $remote_lkp_pack_server:/tmp/
                ssh $remote_lkp_pack_server -C "export LKP_SRC=/tmp/lkp-tests;cd $CCI_SRC/container/lkp-initrd;./build && echo 'y/n'|./run $lkp_tag;rm -rf /tmp/lkp-tests"

                architecture=$(ssh $remote_lkp_pack_server -C "arch")
                rsync_cgz=/srv/upload-files/lkp-tests/$architecture/$lkp_tag.cgz
                rsync -a $remote_lkp_pack_server:$rsync_cgz $rsync_cgz
        }

        chown -R lkp:lkp /srv/upload-files
}

load_cci_defaults
backup_repo "lkp-tests" "$git_branch_lkp"
backup_repo "cbs" "$git_branch_cbs"
install_lkp_tests
upgrade_service
