######################################################################
####function:install appstore
####author:lance_cao
####create date:2019-11
####modify date:2019-11
######################################################################

#!/bin/bash
set -e
echo "[$(date +'%F %H:%M:%S')] [INFO] useage : bash installappstore.sh sharepath sys_user db_type nginx_order"
if [ $# -ne 4 ]; then
  echo "$(basename $0): Missing script argument"
  echo "$(basename $0) [sharepath] [sys_user] [db_type] [nginx_order]"
  exit 1
fi

## ENV ##
pd=$PWD
vsharepath=$1
sys_user=$2
db_type=$3
db_type=${db_type:-pg} # 默认pg
nginx_order=$4
isSharepath=1
if [ -z "$vsharepath" ]; then
  isSharepath=0
  vsharepath=$pd
fi

# 创建appstatic.tar.gz中不存在的文件夹
mkdir -p $vsharepath/appstatic
# 二开路径
mkdir -p $vsharepath/appstatic/appstore/cosmic/cus
# 补丁仓库
mkdir -p $vsharepath/appstatic/patchwarehouse/mc-self-upgrade

# 第一台nginx解压就够了
if [ "${nginx_order}" -le 1 ]; then
  if [ -f "$pd/appstatic.tar.gz" ]; then
    if [ $isSharepath -eq "1" ]; then
      cp appstatic.tar.gz $vsharepath
    fi
    cd $vsharepath && tar -xf appstatic.tar.gz
    # 根据db_type使用哪个
    mv $vsharepath/appstatic/appstore/mc/db/ierp-${db_type}.zip $vsharepath/appstatic/appstore/mc/db/ierp.zip
  fi
fi

# 如果是非root用户先改权限, 不使用chown -R 是因为不要改变其他文件或目录的权限
if [ "$sys_user" != "root" ]; then
  IFS='/' read -r -a path_array <<< "$vsharepath"
  chown_path=""
  for path in ${path_array[@]}; do
    chown_path=${chown_path}/${path}
    chown $sys_user $chown_path
  done
  # /var目录也需要非root用户所属
  chown $sys_user /var
fi

#create link
cd $vsharepath/appstatic
pd=$PWD

# 尝试次数
max_attempts=3
# 当前尝试次数
attempts=0
# 标记变量，用于判断是否创建成功
success=0
# 循环尝试创建软链接
while [ $attempts -lt $max_attempts ]; do
  # 尝试创建软链接
  rm -f /var/appstatic
  runuser - $sys_user -c "ln -s ${pd} /var/appstatic"
  # 检查是否创建成功
  if [ $? -eq 0 ]; then
    echo "软链接创建成功。"
    success=1
    break
  else
    echo "尝试创建软链接失败。"
    attempts=$((attempts + 1))
  fi
done

# 检查是否成功创建软链接
if [ $success -eq 0 ]; then
  echo "/var/appstatic软链接创建失败，请检查Ngnix主机系统配置或手工到主机上创建对应软链接,命令： runuser - $sys_user -c \"ln -s ${pd} /var/appstatic\""
  exit 1
fi

chown -R $sys_user:$sys_user $vsharepath/appstatic
chown -R $sys_user:$sys_user /var/appstatic

# 重启下nginx，发现改完软链接不重启nginx，mc上传补丁卡住，我也不知道为什么
if systemctl is-active nginx.service; then
  systemctl restart nginx
fi
echo "appstore install success "
