#!/bin/bash
npx vite build
# 开发主机（开发环境服务器 有SSH权限至生产环境）
DEV_HOST=root@dbo.fmode.cn
# 生产主机(生产环境服务器)
PROD_HOST=root@8.140.98.43
# 部署路径
DIR_SERVER=/opt/edu-textbook-server

# 资源文件
cp -rf config dist/server/
cp package.json dist/server/
sed -i '/@embedded/d' dist/server/package.json
sed -i '/@embedded/d' dist/server/package.json
cp config.js dist/server/
cp keepalive.js dist/server/
cp -rf cloud/tbook/template dist/server/
cd dist
tar zcvf server.tar.gz ./server
cp server.tar.gz ../../docker/opt/
cd ..

# 压缩部署
ssh $DEV_HOST "mkdir -p $DIR_SERVER"
scp dist/server.tar.gz $DEV_HOST:$DIR_SERVER/
ssh $DEV_HOST "scp -r $DIR_SERVER/server.tar.gz $PROD_HOST:/opt/"
ssh $DEV_HOST "ssh $PROD_HOST \"cd /opt/ && tar zxvf server.tar.gz && cp -rf server/* edu-textbook-server/\"" # 仅安装prod
ssh $DEV_HOST "ssh $PROD_HOST \"cd /opt/ && cp server.tar.gz /var/www/edu-textbook\"" # 仅安装prod


# 部署过程
# ssh $DEV_HOST "mkdir -p $DIR_SERVER"
# scp dist/server/server.js $DEV_HOST:$DIR_SERVER/
# scp ./package.json $DEV_HOST:$DIR_SERVER/
# scp ./config.js $DEV_HOST:$DIR_SERVER/
# ssh $DEV_HOST "scp -r $DIR_SERVER $PROD_HOST:/opt/"

# 启动过程
ssh $DEV_HOST "ssh $PROD_HOST \"cd $DIR_SERVER && ls -lah\"" # 仅安装prod
ssh $DEV_HOST "ssh $PROD_HOST \"cd $DIR_SERVER && npm i --omit=dev --force\"" # 仅安装prod
ssh $DEV_HOST "ssh $PROD_HOST \"cd $DIR_SERVER && pm2 stop server.js\""
ssh $DEV_HOST "ssh $PROD_HOST \"cd $DIR_SERVER && pm2 start server.js\""