#!/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

TAG=$1

[[ -n $TAG ]] && {
    check_tag=$(git -C $LKP_SRC tag -l $TAG)
    if [[ -n $check_tag ]]
    then
        echo "Warning: lkp-tests Tag $TAG already exists."
        echo "It will rollback to it if you want to use it to do the package."
        echo -n "Continue(Y/y) or specify a new one(N/n): "
        read answer

        [[ $answer =~ ^[Nn] ]] && exit
        # case use an existing tag to do the pkg,
        # first roll back to the tag, and then do the pkg.
        git -C $LKP_SRC reset --hard $TAG
    else
        git -C $LKP_SRC tag $TAG
    fi
}

[[ -n $TAG ]] && {
    check_tag=$(git -C $CCI_SRC tag -l $TAG)
    if [[ -n $check_tag ]]
    then
        echo "Warning: cbs Tag $TAG already exists."
        echo "It will rollback to it if you want to use it to do the package."
        echo -n "Continue(Y/y) or specify a new one(N/n): "
        read answer

        [[ $answer =~ ^[Nn] ]] && exit
        # case use an existing tag to do the pkg,
        # first roll back to the tag, and then do the pkg.
        git -C $CCI_SRC reset --hard $TAG
    else
        git -C $CCI_SRC tag $TAG
    fi
}

if [ -d /tmp/$TAG ];then
    rm -rf /tmp/$TAG
fi

target_dirs=(
               /tmp
               /tmp/$TAG/cbs
               /tmp/$TAG/cbs/lib
               /tmp/$TAG/cbs/container
               /tmp/$TAG/cbs/sparrow
               /tmp/$TAG/cbs/sparrow/1-storage
               /tmp/$TAG/lkp-tests
               /tmp/$TAG/lkp-tests/lib 
    )
mkdir -p "${target_dirs[@]}"

cp -r $CCI_SRC/providers /tmp/$TAG/cbs/
cp $CCI_SRC/lib/mq_client.rb /tmp/$TAG/cbs/lib/
cp -r $CCI_SRC/container/ccache /tmp/$TAG/cbs/container/
cp -r $CCI_SRC/container/lkp-initrd /tmp/$TAG/cbs/container/
cp -r $CCI_SRC/sparrow/1-storage/tiny /tmp/$TAG/cbs/sparrow/1-storage/
cp $CCI_SRC/container/defconfig.rb /tmp/$TAG/cbs/container/
cp $CCI_SRC/container/defconfig.sh /tmp/$TAG/cbs/container/
echo 'cbs repo cp success'

cp -r $LKP_SRC/hosts /tmp/$TAG/lkp-tests/
cp $LKP_SRC/lib/yaml.sh /tmp/$TAG/lkp-tests/lib/
echo 'lkp-test repo cp success'

tar -zcvf /tmp/$TAG.tar.gz /tmp/$TAG

echo "pack ebs repos success result:/tmp/$TAG"