#!/bin/sh

if [ $# -ne 1 ]
then
    echo "usage: $0 <linux user>"
    exit
fi

echo "#### Please make sure that the user you entered  ####"
echo "#### is consistenct with the old one used as the ####"
echo "#### owner to deploy EM service, which you can   ####"
echo "#### check from the genrated config.yaml         ####"
read -r -p "Do you want to continue? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    echo "start updating"
else
    echo "do nothing"
    exit 1
fi

USER=$1

script_dir=$(cd $(dirname $0) && pwd)

EM_PACKAGE_PATH=${script_dir}.tar.gz
EM_PACKAGE_NAME=$(basename -s .tar.gz $EM_PACKAGE_PATH)

echo "##### prepare temp EM REPO /home/${USER}/${EM_PACKAGE_NAME} started #####"
em_repo_dir=/home/${USER}/em-repo
if [ ! -d "$em_repo_dir" ]; then
    echo "EM REPO ${em_repo_dir} does not exist, you might need to use install.sh." 
    exit 1
fi

em_temp_repo_dir=/home/${USER}/${EM_PACKAGE_NAME}
if [ -d "$em_temp_repo_dir" ]; then
    echo "temp EM REPO ${em_temp_repo_dir} has already existed, which means ${em_repo_dir} might have already been updated." 
    exit 1
fi
cp -r $script_dir $em_temp_repo_dir
chmod -R 777 $em_temp_repo_dir
echo "##### prepare temp EM REPO /home/${USER}/${EM_PACKAGE_NAME} finished #####"

bin_dir=/home/${USER}/.tiup/bin
EM_TIUP_HOME=/home/${USER}/.em

cd /home/${USER}

echo "##### update em mirror ${em_repo_dir} started #####"
su - $USER << EOF
TIUP_HOME=${EM_TIUP_HOME} "${bin_dir}/tiup" mirror merge ${em_temp_repo_dir}
EOF
echo "##### update em mirror ${em_repo_dir} finished #####"

rm -rf ${em_temp_repo_dir}
