#!/bin/bash

#### Create WP Site
#### v3 自动从临时服务器拉取模板站shell脚本,并自动化部署
#### Author: chenpeiqing
#### Date: 2024-11-18
#### Usage: sh create_wp_tempate.sh [2408210vakv9]
#### 示例: sh create-wpsite.sh 2408210vakv9 wp063

#模板 site code
SITE_CODE=$1

RDS_HOST='127.0.0.1'
RDS_ADMIN='root'
RDS_PWD='Initial0_123'

#从临时服务器下载项目文件
echo '从临时服务器下载项目文件'
scp  -i /home/ubuntu/ningxia.pem -P 9922 ec2-user@52.83.132.56:/home/ec2-user/template_temp/$SITE_CODE.tar.gz /home/ubuntu/template_temp
echo "从临时服务器下载项目文件花费:"$((end_time - start_time))"s"
echo '从临时服务器下载项目文件结束'

#移动项目文件到目标目录
mv /home/ubuntu/template_temp/$SITE_CODE.tar.gz /usr/local/wwwtemplate/
echo "移动项目文件到目标目录花费:"$((end_time - start_time))"s"
echo "解压模板站"
cd /usr/local/wwwtemplate/
tar -xzf $SITE_CODE.tar.gz
#解压后删除压缩文件
rm -f $SITE_CODE.tar.gz
echo "解压模板站花费:"$((end_time - start_time))"s"

#从临时服务器下载数据库
echo '从临时服务器下载数据库'
scp  -i /home/ubuntu/ningxia.pem -P 9922 ec2-user@52.83.132.56:/home/ec2-user/template_temp/$SITE_CODE.sql /home/ubuntu/template_temp
echo "从临时服务器下载数据库花费:"$((end_time - start_time))"s"
echo '从临时服务器下载数据库结束'

#创建数据库,赋权
echo 'create_database_start'
start_time=$(date +'%s')
mysql -h$RDS_HOST -u$RDS_ADMIN -p$RDS_PWD<< EOF
  DROP DATABASE IF EXISTS $SITE_CODE;
  CREATE DATABASE $SITE_CODE CHARACTER SET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  GRANT ALL ON $SITE_CODE.* TO 'adweb'@'localhost';
  FLUSH PRIVILEGES;
  exit
EOF
end_time=$(date +'%s')
echo "创建数据库花费:"$((end_time - start_time))"s"
echo 'create_database_end'

#导入数据库
start_time=$(date +'%s')
mysql -u$RDS_ADMIN -p$RDS_PWD $SITE_CODE < /home/ubuntu/template_temp/$SITE_CODE.sql
end_time=$(date +'%s')
echo "【"$SITE_CODE"】网站导入数据库完成,共计花费:"$((end_time - start_time))"s"

#更新数据库连接配置
echo 'update_wp-config_start'
start_time=$(date +'%s')

sed -i "s:FILE_NAME:$SITE_CODE:g" /usr/local/wwwtemplate/$SITE_CODE/domain.txt
sed -i "s:'RqBQxctjakHCJVq8kmmYHQKZQGU4YMUH':'2024_RqBQxctjakHCJVq8kmmYHQKZQGU4YMUH':g" /usr/local/wwwtemplate/$SITE_CODE/wp-config.php
end_time=$(date +'%s')
echo "更新WP配置文件花费:"$((end_time - start_time))"s"
echo 'update_wp-config_end'

# 替换老域名到数据库 wp-cli
echo 'UPDATE_WP_DOMAIN_START'
start_time=$(date +'%s')
cd /usr/local/wwwtemplate/$SITE_CODE
cp /opt/adweb3/config/wp-cli.phar ./
php ./wp-cli.phar search-replace "https://$SITE_CODE.adwebcloud.com" "https://$SITE_CODE.adweb3.topxuetang.com" --allow-root
rm -rf wp-cli.phar
end_time=$(date +'%s')
echo "更新WP域名花费:"$((end_time - start_time))"s"
echo 'UPDATE_WP_DOMAIN_END'


# 创建nginx配置文件,并reload nginx
#nginx
echo 'UPDATE_NGINX_START'
start_time=$(date +'%s')

cp /opt/adweb3/nginx_template/wp-template.conf /usr/local/openresty/nginx/vhost/template/$SITE_CODE.conf
sed -i "s:SITE_CODE:$SITE_CODE:g" /usr/local/openresty/nginx/vhost/template/$SITE_CODE.conf

echo "开始重启nginx配置"
/usr/local/openresty/nginx/sbin/nginx -s reload
echo "nginx配置重启完成"echo "开始重启nginx配置"

# 修改项目所有者为www-data
chown -R www-data:www-data /usr/local/wwwtemplate/$SITE_CODE/