#!/usr/bin/env bash
# -------------------------------------------------------------------------------
# Filename:    java_deploy.sh
# Revision:    1.0
# Date:        2016/09
# Author:      Xiaolin.zhu
# Description: 该脚本调用其他脚本实现js项目的自动化部署。目前只有deploy_app-backend jenkins job使用了该脚本。
# -------------------------------------------------------------------------------
source ~/.bash_profile

repo_url=$1
module_name=$2
branch_name=$3
target_host=$4
checkout_branch=$5
remote_copy=$6
restart=$7
re_load_config=$8

work_path=/home/quant_group
backup_path=/home/quant_group/remote_backup
utils_path=/home/quant_group/qa-deploy-utils

echo "job name is ${JOB_NAME}"

if [ "$checkout_branch" = true ]; then
    echo "Step 2: checkout branch: $branch_name"

    if [ -d  ${module_name} ]
    then
        echo "Step 2.2:  rm -rf ${module_name}"
        rm -rf ${module_name}
    fi

    echo "Step 2.3:  git clone $repo_url"
    git clone $repo_url

    cd $module_name
    sh ${utils_path}/sh-utils/center/1_branch_checkout.sh $branch_name
else
    echo "Step 2: skip checkout branch: $branch_name"
fi

if [ "$remote_copy" = true ]; then
    echo "Step 3: remote copy project"
    cd ..
    mkdir -p ${backup_path}

    if [ -f ${backup_path}/${module_name}.tar.gz ]
    then
        echo "Step 3.1: rm -f ${backup_path}/${module_name}.tar.gz"
        rm -f ${backup_path}/${module_name}.tar.gz
    fi

    echo "Step 3.3: tar cfz ${backup_path}/${module_name}.tar.gz ${module_name}"
    tar cfz ${backup_path}/${module_name}.tar.gz ${module_name}

    echo "Step 3.4: remote copy"
    scp ${backup_path}/${module_name}.tar.gz root@${target_host}:/home/quant_group/remote_backup/

else
    echo "Step 3: skip remote copy project: ${module_name}.tar.gz"
fi

if [ "$restart" = true ]; then
    echo "Step 4: restart"
    ssh root@${target_host} sh ${utils_path}/sh-utils/worker/other_restart.sh ${module_name} $target_host $re_load_config
else
    echo "Step 4: skip restart"
fi
