#!/bin/sh

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

echo "#### Please make sure that you have editted user ####"
echo "#### in config_template.yaml as you want, and don't #"
echo "#### edit {ip} as it will be auto generated.     ####"
echo "#### The user is 'tidb' by default, which will be ###"
echo "#### used as the owner to deploy EM service.     ####"
echo "#### If you have installed EM before, make sure  ####"
echo "#### that the user is consistenct with the old one. #"
echo "#### After install.sh is run, a config.yaml file ####"
echo "#### will be generated under /home/<user>/, and  ####"
echo "#### please don't edit this file.                ####"
read -r -p "Do you want to continue? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
    echo "start installing"
else
    echo "do nothing"
    exit 1
fi

IP=$1

case $(uname -s) in
    Linux|linux) os=linux ;;
    *) os= ;;
esac

if [ -z "$os" ]; then
    echo "OS $(uname -s) not supported." >&2
    exit 1
fi

case $(uname -m) in
    amd64|x86_64) arch=amd64 ;;
    *) arch= ;;
esac

if [ -z "$arch" ]; then
    echo "Architecture  $(uname -m) not supported." >&2
    exit 1
fi

bin_dir=/usr/local/bin

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

CONFIG_TEMPLATE_YAML=$script_dir/config_template.yaml
if [ ! -f "$CONFIG_TEMPLATE_YAML" ]; then
    echo "$CONFIG_TEMPLATE_YAML does not exist."
    exit 1
fi

EM_PACKAGE_NAME=$(basename $script_dir)

USER=$(cat $CONFIG_TEMPLATE_YAML | grep user | sed 's/.*user: .*"\(.*\)".*/\1/')

echo "##### add user $USER started #####"
useradd $USER
echo "##### add user $USER finished #####"

echo "##### prepare TiDB REPO /em-data/tidb-repo started #####"
tidb_repo_dir=/em-data/tidb-repo
if [ ! -d "$tidb_repo_dir" ]; then
    mkdir -p $tidb_repo_dir
fi
chmod -R 777 $tidb_repo_dir
echo "##### prepare TiDB REPO /em-data/tidb-repo finished #####"

echo "##### prepare EM REPO /home/${USER}/em-repo started #####"
em_repo_dir=/home/${USER}/em-repo
if [ -d "$em_repo_dir" ]; then
    echo "EM REPO ${em_repo_dir} exists, you might need to either use update.sh or uninstall.sh." 
    exit 1
fi
mkdir -p $em_repo_dir
chmod -R 777 $em_repo_dir

echo "##### dynamically prepare TiUniManager cert started #####"
em_all_cert_dir=/em-data/em-cert
common_cert_dir=${em_all_cert_dir}/common
etcd_cert_dir=${em_all_cert_dir}/etcd
mkdir -p ${em_all_cert_dir}
mkdir -p ${common_cert_dir}
mkdir -p ${etcd_cert_dir}

cd ${common_cert_dir}
openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -days 1024 -out rootCA.pem -subj '/CN=em-server/O=PingCAP/C=CN'
openssl genrsa -out server.key 2048
openssl req -new -key server.key -out server.csr -subj '/CN=em-server/O=PingCAP/C=CN'
openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 3650
echo $RANDOM | md5sum | head -c 32 > aes.key

cfsslBinPath=${script_dir}/tools
cfsslConfigPath=${script_dir}/configs
cd ${etcd_cert_dir}
${cfsslBinPath}/cfssl gencert -initca ${cfsslConfigPath}/ca-csr.json | ${cfsslBinPath}/cfssljson -bare etcd-ca -
${cfsslBinPath}/cfssl gencert -ca=etcd-ca.pem -ca-key=etcd-ca-key.pem --config=${cfsslConfigPath}/ca-config.json \
-profile=server ${cfsslConfigPath}/server.json | ${cfsslBinPath}/cfssljson  -bare etcd-server

chown -R ${USER}:${USER} ${em_all_cert_dir}
em_cert_dir=/home/${USER}/em-cert
mkdir -p ${em_cert_dir}
cp ${common_cert_dir}/aes.key ${em_cert_dir}
cp ${common_cert_dir}/server.crt ${em_cert_dir}
cp ${common_cert_dir}/server.csr ${em_cert_dir}
cp ${common_cert_dir}/server.key ${em_cert_dir}
cp ${etcd_cert_dir}/etcd-ca.pem ${em_cert_dir}
cp ${etcd_cert_dir}/etcd-server-key.pem ${em_cert_dir}
cp ${etcd_cert_dir}/etcd-server.pem ${em_cert_dir}
chown -R ${USER}:${USER} ${em_cert_dir}
echo "##### dynamically prepare TiUniManager cert finished #####"

em_temp_repo_dir=/home/${USER}/${EM_PACKAGE_NAME}
cp -r $script_dir $em_temp_repo_dir
chmod -R 777 $em_temp_repo_dir
echo "##### prepare EM REPO /home/${USER}/em-repo finished #####"

CONFIG_YAML=/home/$USER/config.yaml
echo "##### generate config $CONFIG_YAML started #####"
cp $CONFIG_TEMPLATE_YAML $CONFIG_YAML
chmod 666 $CONFIG_YAML
sed -i "s/{ip}/$IP/g" $CONFIG_YAML
echo "##### generate config $CONFIG_YAML finished #####"

cd /home/${USER}

echo "##### prepare TiDB TIUP_HOME started #####"
TIDB_TIUP_HOME=/home/${USER}/.tiup
tidb_bin_dir=${TIDB_TIUP_HOME}/bin
su - $USER << EOF
mkdir -p "${tidb_bin_dir}"
EOF
echo "##### prepare TiDB TIUP_HOME finished #####"

echo "##### prepare EM TIUP_HOME started #####"
EM_TIUP_HOME=/home/$USER/.em
em_bin_dir=${EM_TIUP_HOME}/bin
su - $USER << EOF
mkdir -p "${em_bin_dir}"
EOF
echo "##### prepare EM TIUP_HOME finished #####"

echo "##### check depends tar started #####"
su - $USER << EOF
check_depends() {
    pass=0
    command -v tar >/dev/null || {
        echo "Dependency check failed: please install 'tar' before proceeding."
        pass=1
    }
    return ${pass}
}
if ! check_depends; then
    exit 1
fi
EOF
echo "##### check depends tar finished #####"

install_binary() {
  echo "##### install tiup binary to ${tidb_bin_dir} started #####"
  tar -zxf "${em_temp_repo_dir}/tiup-${os}-${arch}.tar.gz" -C "${tidb_bin_dir}" || return 1
  echo "##### install tiup binary to ${tidb_bin_dir} finished #####"
  # Use the offline root.json
  echo "##### copy root.json to ${tidb_bin_dir}" started #####"
  cp "${em_temp_repo_dir}/root.json" "${tidb_bin_dir}" || return 1
  chmod 777 ${tidb_bin_dir}/root.json
  echo "##### copy root.json to ${tidb_bin_dir}" finished #####"
  # Remove old manifests
  echo "##### remove old manifests in ${TIDB_TIUP_HOME} started #####"
  rm -rf ${TIDB_TIUP_HOME}/manifests
  echo "##### remove old manifests in ${TIDB_TIUP_HOME} finished #####"
  echo "##### install TiUP to ${bin_dir} started #####"
  install -Dm755 ${tidb_bin_dir}/tiup ${bin_dir}
  echo "##### install TiUP to ${bin_dir} finished #####"
  return 0
}
if ! install_binary; then
    echo "Failed to download and/or extract tiup archive."
    exit 1
fi
chmod 777 "${tidb_bin_dir}/tiup"

su - $USER << EOF
# telemetry is not needed for offline installations
"${bin_dir}/tiup" telemetry disable
EOF

echo "##### init em mirror ${em_repo_dir} started #####"
su - $USER << EOF
TIUP_HOME=${EM_TIUP_HOME} "${bin_dir}/tiup" mirror init ${em_repo_dir}
TIUP_HOME=${EM_TIUP_HOME} "${bin_dir}/tiup" mirror set ${em_repo_dir}
# rm -f ${EM_TIUP_HOME}/keys/private.json
cp ${em_temp_repo_dir}/set_owner.sh ${em_repo_dir}
cd ${em_repo_dir}
sh set_owner.sh ${EM_TIUP_HOME} ${bin_dir} em
cp ${em_repo_dir}/keys/* ${EM_TIUP_HOME}/keys/
TIUP_HOME=${EM_TIUP_HOME} "${bin_dir}/tiup" mirror merge ${em_temp_repo_dir}
EOF
echo "##### init em mirror ${em_repo_dir} finished #####"

echo "##### init tidb mirror ${tidb_repo_dir} started #####"
su - $USER << EOF
TIUP_HOME=${TIDB_TIUP_HOME} "${bin_dir}/tiup" mirror init ${tidb_repo_dir}
TIUP_HOME=${TIDB_TIUP_HOME} "${bin_dir}/tiup" mirror set ${tidb_repo_dir}
# rm -f ${TIDB_TIUP_HOME}/keys/private.json
cp ${em_temp_repo_dir}/set_owner.sh ${tidb_repo_dir}
cd ${tidb_repo_dir}
sh set_owner.sh ${TIDB_TIUP_HOME} ${bin_dir} pingcap
cp ${tidb_repo_dir}/keys/* ${TIDB_TIUP_HOME}/keys/
cd ${em_temp_repo_dir}
TIUP_HOME=${TIDB_TIUP_HOME} "${bin_dir}/tiup" mirror publish cluster v1.9.0 cluster-v1.9.0-linux-amd64.tar.gz tiup-cluster --arch amd64 --os linux --desc "tiup-cluster tools" --standalone
EOF
echo "##### init tidb mirror ${tidb_repo_dir} finished #####"

rm -rf ${em_temp_repo_dir}

bold=$(tput bold 2>/dev/null)
sgr0=$(tput sgr0 2>/dev/null)

# Reference: https://stackoverflow.com/questions/14637979/how-to-permanently-set-path-on-linux-unix
shell=$(echo ${SHELL} | awk 'BEGIN {FS="/";} { print $NF }')
echo "Detected shell: ${bold}${shell}${sgr0}"
if [ -f "/home/${USER}/.${shell}_profile" ]; then
    PROFILE=/home/${USER}/.${shell}_profile
elif [ -f "/home/${USER}/.${shell}_login" ]; then
    PROFILE=/home/${USER}/.${shell}_login
elif [ -f "/home/${USER}/.${shell}rc" ]; then
    PROFILE=/home/${USER}/.${shell}rc
else
    PROFILE=/home/${USER}/.profile
fi
echo "Shell profile:  ${bold}${PROFILE}${sgr0}"

su - $USER << EOF
printf 'export PATH=%s:\$PATH\n' "${bin_dir}" >> "${PROFILE}"
echo "${PROFILE} has been modified to to add tiup to PATH"
echo "open a new terminal or ${bold}source ${PROFILE}${sgr0} to use it"
echo "Installed path: ${bold}${bin_dir}/tiup${sgr0}"
echo "====================================================================="
echo "Please follow the instruction below to deploy em: "
echo "1. Switch user:  ${bold}su - $USER${sgr0}"
echo "2. ${bold}source ${PROFILE}${sgr0}"
echo "3. Have a try:   ${bold}TIUP_HOME=${EM_TIUP_HOME} tiup em list${sgr0}"
echo "===================================================================="
EOF
