#!/usr/bin/env bash
# Author:  EinicYeo <einicyeo AT gmail.com>
# BLOG:  https://www.infvie.com
#
# Notes: EnvoyinStack for CentOS/RedHat 6+

export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
clear
printf "
#######################################################################
#               Author:  EinicYeo <einicyeo AT gmail.com>              #
#                   EnvoyinStack for CentOS/RedHat 6+                   #
#                     Setup the backup parameters                      #
#      For more information please visit https://www.infvie.com        #
#######################################################################
"
# Check if user is root
[ $(id -u) != "0" ] && { echo "${CFAILURE}Error: You must be root to run this script${CEND}"; exit 1; }

envoyinstack_dir=$(dirname "`readlink -f $0`")
pushd ${envoyinstack_dir} > /dev/null
. ./config/options.conf
. ./include/color.sh
. ./include/check_os.sh
. ./include/check_dir.sh

while :; do echo
  echo 'Please select your backup destination:'
  echo -e "\t${CMSG}1${CEND}. Localhost"
  echo -e "\t${CMSG}2${CEND}. Remote host"
  echo -e "\t${CMSG}3${CEND}. Aliyun OSS"
  read -e -p "Please input numbers:(Default 1 press Enter) " desc_bk
  desc_bk=${desc_bk:-'1'}
  array_desc=(${desc_bk})
  array_all=(1 2 3 )
  for v in ${array_desc[@]}
  do
    [ -z "`echo ${array_all[@]} | grep -w ${v}`" ] && desc_flag=1
  done
  if [ "${desc_flag}" == '1' ]; then
    unset desc_flag
    echo; echo "${CWARNING}input error! Please only input number 1 2 3 and so on${CEND}"; echo
    continue
  else
    sed -i 's@^backup_destination=.*@backup_destination=@' ./config/options.conf
    break
  fi
done

[ -n "`echo ${desc_bk} | grep -w 1`" ] && sed -i 's@^backup_destination=.*@backup_destination=local@' ./config/options.conf
[ -n "`echo ${desc_bk} | grep -w 2`" ] && sed -i 's@^backup_destination=.*@&,remote@' ./config/options.conf
[ -n "`echo ${desc_bk} | grep -w 3`" ] && sed -i 's@^backup_destination=.*@&,oss@' ./config/options.conf
sed -i 's@^backup_destination=,@backup_destination=@' ./config/options.conf

while :; do echo
  echo 'Please select your backup content:'
  echo -e "\t${CMSG}1${CEND}. Only Database"
  echo -e "\t${CMSG}2${CEND}. Only Website"
  echo -e "\t${CMSG}3${CEND}. Database and Website"
  read -e -p "Please input a number:(Default 1 press Enter) " content_bk
  content_bk=${content_bk:-1}
  if [[ ! ${content_bk} =~ ^[1-3]$ ]]; then
    echo "${CWARNING}input error! Please only input number 1~3${CEND}"
  else
    break
  fi
done

[ "${content_bk}" == '1' ] && sed -i 's@^backup_content=.*@backup_content=db@' ./config/options.conf
[ "${content_bk}" == '2' ] && sed -i 's@^backup_content=.*@backup_content=web@' ./config/options.conf
[ "${content_bk}" == '3' ] && sed -i 's@^backup_content=.*@backup_content=db,web@' ./config/options.conf

if [ -n "`echo ${desc_bk} | grep -Ew '1|2'`" ]; then
  while :; do echo
    echo "Please enter the directory for save the backup file: "
    read -e -p "(Default directory: ${backup_dir}): " new_backup_dir
    new_backup_dir=${new_backup_dir:-${backup_dir}}
    if [ -z "`echo ${new_backup_dir}| grep '^/'`" ]; then
      echo "${CWARNING}input error! ${CEND}"
    else
      break
    fi
  done
  sed -i "s@^backup_dir=.*@backup_dir=${new_backup_dir}@" ./config/options.conf
fi

while :; do echo
  echo "Please enter a valid backup number of days: "
  read -e -p "(Default days: 5): " expired_days
  expired_days=${expired_days:-5}
  [ -n "`echo ${expired_days} | sed -n "/^[0-9]\+$/p"`" ] && break || echo "${CWARNING}input error! Please only enter numbers! ${CEND}"
done
sed -i "s@^expired_days=.*@expired_days=${expired_days}@" ./config/options.conf

if [ "${content_bk}" != '2' ]; then
  databases=`${db_install_dir}/bin/mysql -uroot -p$dbrootpwd -e "show databases\G" | grep Database | awk '{print $2}' | grep -Evw "(performance_schema|information_schema|mysql|sys)"`
  while :; do echo
    echo "Please enter one or more name for database, separate multiple database names with commas: "
    read -e -p "(Default database: `echo $databases | tr ' ' ','`) " db_name
    db_name=`echo ${db_name} | tr -d ' '`
    [ -z "${db_name}" ] && db_name="`echo $databases | tr ' ' ','`"
    D_tmp=0
    for D in `echo ${db_name} | tr ',' ' '`
    do
      [ -z "`echo $databases | grep -w $D`" ] && { echo "${CWARNING}$D was not exist! ${CEND}" ; D_tmp=1; }
    done
    [ "$D_tmp" != '1' ] && break
  done
  sed -i "s@^db_name=.*@db_name=${db_name}@" ./config/options.conf
fi

if [ "${content_bk}" != '1' ]; then
  websites=`ls ${wwwroot_dir}`
  while :; do echo
    echo "Please enter one or more name for website, separate multiple website names with commas: "
    read -e -p "(Default website: `echo $websites | tr ' ' ','`) " website_name
    website_name=`echo ${website_name} | tr -d ' '`
    [ -z "${website_name}" ] && website_name="`echo $websites | tr ' ' ','`"
    W_tmp=0
    for W in `echo ${website_name} | tr ',' ' '`
    do
      [ ! -e "${wwwroot_dir}/$W" ] && { echo "${CWARNING}${wwwroot_dir}/$W not exist! ${CEND}" ; W_tmp=1; }
    done
    [ "$W_tmp" != '1' ] && break
  done
  sed -i "s@^website_name=.*@website_name=${website_name}@" ./config/options.conf
fi

echo
echo "You have to backup the content:"
[ "${content_bk}" != '2' ] && echo "Database: ${CMSG}${db_name}${CEND}"
[ "${content_bk}" != '1' ] && echo "Website: ${CMSG}${website_name}${CEND}"

if [ -n "`echo ${desc_bk} | grep -w 2`" ]; then
  > tools/iplist.txt
  while :; do echo
    read -e -p "Please enter the remote host address: " remote_address
    [ -z "${remote_address}" -o "${remote_address}" == '127.0.0.1' ] && continue
    echo
    read -e -p "Please enter the remote host port(Default: 22) : " remote_port
    remote_port=${remote_port:-22}
    echo
    read -e -p "Please enter the remote host user(Default: root) : " remote_user
    remote_user=${remote_user:-root}
    echo
    read -e -p "Please enter the remote host password: " remote_password
    IPcode=$(echo "ibase=16;$(echo "${remote_address}" | xxd -ps -u)"|bc|tr -d '\\'|tr -d '\n')
    Portcode=$(echo "ibase=16;$(echo "${remote_port}" | xxd -ps -u)"|bc|tr -d '\\'|tr -d '\n')
    PWcode=$(echo "ibase=16;$(echo "$remote_password" | xxd -ps -u)"|bc|tr -d '\\'|tr -d '\n')
    [ -e "~/.ssh/known_hosts" ] && grep ${remote_address} ~/.ssh/known_hosts | sed -i "/${remote_address}/d" ~/.ssh/known_hosts
    ./tools/mssh.exp ${IPcode}P ${remote_user} ${PWcode}P ${Portcode}P true 10
    if [ $? -eq 0 ]; then
      [ -z "`grep ${remote_address} tools/iplist.txt`" ] && echo "${remote_address} ${remote_port} ${remote_user} $remote_password" >> tools/iplist.txt || echo "${CWARNING}${remote_address} has been added! ${CEND}"
      while :; do
        read -e -p "Do you want to add more host ? [y/n]: " morehost_flag
        if [[ ! ${morehost_flag} =~ ^[y,n]$ ]]; then
          echo "${CWARNING}input error! Please only input 'y' or 'n'${CEND}"
        else
          break
        fi
      done
      [ "${morehost_flag}" == 'n' ] && break
    fi
  done
fi

if [ -n "`echo ${desc_bk} | grep -w 3`" ]; then
  if [ ! -e "/usr/local/bin/ossutil" ]; then
    pushd ${envoyinstack_dir}/src/backup > /dev/null
    cp -rf ossutil64 /usr/local/bin/ossutil
    chmod +x /usr/local/bin/ossutil
    popd > /dev/null
  fi
  while :; do echo
    echo 'Please select your backup aliyun datacenter:'
    echo -e "\t ${CMSG}1${CEND}. cn-hangzhou-华东 1 (杭州)         ${CMSG}2${CEND}. cn-shanghai-华东 2 (上海)"
    echo -e "\t ${CMSG}3${CEND}. cn-qingdao-华北 1 (青岛)          ${CMSG}4${CEND}. cn-beijing-华北 2 (北京)"
    echo -e "\t ${CMSG}5${CEND}. cn-zhangjiakou-华北 3 (张家口)    ${CMSG}6${CEND}. cn-huhehaote-华北 5(呼和浩特)"
    echo -e "\t ${CMSG}7${CEND}. cn-shenzhen-华南 1 (深圳)         ${CMSG}8${CEND}. cn-chengdu-西南 1（成都）"
    echo -e "\t ${CMSG}9${CEND}. cn-hongkong-香港                 ${CMSG}10${CEND}. us-west-美西 1 (硅谷)"
    echo -e "\t${CMSG}11${CEND}. us-east-美东 1 (弗吉尼亚)        ${CMSG}12${CEND}. ap-southeast-亚太东南 1 (新加坡)"
    echo -e "\t${CMSG}13${CEND}. ap-southeast-亚太东南 2 (悉尼)   ${CMSG}14${CEND}. ap-southeast-亚太东南 3 (吉隆坡)"
    echo -e "\t${CMSG}15${CEND}. ap-southeast-亚太东南 5 (雅加达) ${CMSG}16${CEND}. ap-northeast-亚太东北 1 (日本)"
    echo -e "\t${CMSG}17${CEND}. ap-south-亚太南部 1 (孟买)       ${CMSG}18${CEND}. eu-central-欧洲中部 1 (法兰克福)"
    echo -e "\t${CMSG}19${CEND}. eu-west-英国（伦敦）             ${CMSG}20${CEND}. me-east-中东东部 1 (迪拜)"
    read -e -p "Please input a number:(Default 1 press Enter) " Location
    Location=${Location:-1}
    if [[ "${Location}" =~ ^[1-9]$|^1[0-9]$|^20$ ]]; then
      break
    else
      echo "${CWARNING}input error! Please only input number 1~20${CEND}"
    fi
  done
  [ "${Location}" == '1' ] && Host=oss-cn-hangzhou-internal.aliyuncs.com
  [ "${Location}" == '2' ] && Host=oss-cn-shanghai-internal.aliyuncs.com
  [ "${Location}" == '3' ] && Host=oss-cn-qingdao-internal.aliyuncs.com
  [ "${Location}" == '4' ] && Host=oss-cn-beijing-internal.aliyuncs.com
  [ "${Location}" == '5' ] && Host=oss-cn-zhangjiakou-internal.aliyuncs.com
  [ "${Location}" == '6' ] && Host=oss-cn-huhehaote-internal.aliyuncs.com
  [ "${Location}" == '7' ] && Host=oss-cn-shenzhen-internal.aliyuncs.com
  [ "${Location}" == '8' ] && Host=oss-cn-chengdu-internal.aliyuncs.com
  [ "${Location}" == '9' ] && Host=oss-cn-hongkong-internal.aliyuncs.com
  [ "${Location}" == '10' ] && Host=oss-us-west-1-internal.aliyuncs.com
  [ "${Location}" == '11' ] && Host=oss-us-east-1-internal.aliyuncs.com
  [ "${Location}" == '12' ] && Host=oss-ap-southeast-1-internal.aliyuncs.com
  [ "${Location}" == '13' ] && Host=oss-ap-southeast-2-internal.aliyuncs.com
  [ "${Location}" == '14' ] && Host=oss-ap-southeast-3-internal.aliyuncs.com
  [ "${Location}" == '15' ] && Host=oss-ap-southeast-5-internal.aliyuncs.com
  [ "${Location}" == '16' ] && Host=oss-ap-northeast-1-internal.aliyuncs.com
  [ "${Location}" == '17' ] && Host=oss-ap-south-1-internal.aliyuncs.com
  [ "${Location}" == '18' ] && Host=oss-eu-central-1-internal.aliyuncs.com
  [ "${Location}" == '19' ] && Host=oss-eu-west-1-internal.aliyuncs.com
  [ "${Location}" == '20' ] && Host=oss-me-east-1-internal.aliyuncs.com
  [ "$(./include/check_port.py ${Host} 80)" == "False" ] && Host=`echo ${Host} | sed 's@-internal@@g'`
  [ -e "/root/.ossutilconfig" ] && rm -f /root/.ossutilconfig
  while :; do echo
    read -e -p "Please enter the aliyun oss Access Key ID: " KeyID
    [ -z "${KeyID}" ] && continue
    echo
    read -e -p "Please enter the aliyun oss Access Key Secret: " KeySecret
    [ -z "${KeySecret}" ] && continue
    /usr/local/bin/ossutil ls -e ${Host} -i ${KeyID} -k ${KeySecret} > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      /usr/local/bin/ossutil config -e ${Host} -i ${KeyID} -k ${KeySecret} > /dev/null 2>&1
      while :; do echo
        read -e -p "Please enter the aliyun oss bucket object: " OSS_BUCKET
        /usr/local/bin/ossutil mkdir oss://${OSS_BUCKET} > /dev/null 2>&1
        if [ $? -eq 0 ]; then
          echo "${CMSG}Bucket object oss://${OSS_BUCKET}/ created${CEND}"
          sed -i "s@^oss_bucket=.*@oss_bucket=${OSS_BUCKET}@" ./config/options.conf
          break
        else
          echo "${CWARNING}[${OSS_BUCKET}] already exists, You need to use the OSS Console to create a bucket for storing.${CEND}"
        fi
      done
      break
    fi
  done
fi
