smart_ims/scripts/nas/update_smartims.sh

140 lines
4.5 KiB
Bash

#!/bin/bash
# ==========================================
# Smart IMS NAS Update Script (Revised)
# 작성일: 2026-01-26
# ==========================================
# 1. 환경 설정
PROJECT_DIR="/volume1/web/smartims"
BACKUP_DIR="/volume1/smart_ims"
SERVER_DIR="${PROJECT_DIR}/server"
DATE_STAMP=$(date +%Y%m%d_%H%M%S)
# DB 접속 정보
DB_USER="choibk"
DB_PORT="3307"
DB_NAME="sokuree_platform_prod"
DB_HOST="127.0.0.1" # 호스트 명시 (필수)
MYSQL_BIN="/usr/local/mariadb10/bin"
# 로그 파일 설정
mkdir -p "${BACKUP_DIR}/logs"
LOG_FILE="${BACKUP_DIR}/logs/update_${DATE_STAMP}.log"
exec > >(tee -a "${LOG_FILE}") 2>&1
echo "=============================================="
echo "[Update] Started at $(date)"
echo "=============================================="
# 2. .env에서 DB 비밀번호 추출 (Node.js 활용으로 특수문자/따옴표 안전 처리)
if [ -f "${SERVER_DIR}/.env" ]; then
cd "${SERVER_DIR}"
# node 명령어로 파싱하여 쉘 특수문자 이슈 회피
DB_PASS=$(node -e "try{const fs=require('fs');const c=fs.readFileSync('.env','utf8');const m=c.match(/^DB_PASSWORD=(.*)$/m);if(m){let p=m[1].trim();if((p.startsWith('\"')&&p.endsWith('\"'))||(p.startsWith(\"'\")&&p.endsWith(\"'\"))){p=p.slice(1,-1);}process.stdout.write(p);}}catch(e){}")
if [ -z "$DB_PASS" ]; then
echo "[Error] Could not retrieve DB_PASSWORD from .env"
exit 1
fi
echo "[Info] DB Password loaded (Length: ${#DB_PASS})"
else
echo "[Error] .env file not found at ${SERVER_DIR}/.env"
exit 1
fi
# 백업 디렉토리 생성
mkdir -p "${BACKUP_DIR}"
# ==========================================
# 🚨 [STEP 1] 데이터 백업
# ==========================================
echo "[Step 1] Creating Backups..."
# 1-1. 이미지 백업
if [ -d "${PROJECT_DIR}/server/uploads" ]; then
cd "${PROJECT_DIR}"
TAR_NAME="backup_images_${DATE_STAMP}.tar.gz"
echo " - Backing up images..."
tar -czf "${BACKUP_DIR}/${TAR_NAME}" server/uploads/
else
echo " - [Warning] Uploads directory not found. Skipping image backup."
fi
# 1-2. DB 백업
SQL_NAME="backup_db_${DATE_STAMP}.sql"
echo " - Backing up database..."
# -h 127.0.0.1 옵션 추가 및 비밀번호 인자 방식 변경
"${MYSQL_BIN}/mysqldump" -h "${DB_HOST}" -u "${DB_USER}" "-p${DB_PASS}" --port "${DB_PORT}" "${DB_NAME}" --single-transaction --quick --lock-tables=false > "${BACKUP_DIR}/${SQL_NAME}" 2>/dev/null
if [ $? -ne 0 ]; then
echo "[Error] Database backup failed! Please check:"
echo " 1. DB Port ($DB_PORT) matches MariaDB 10 port."
echo " 2. DB Password in .env is correct."
echo " 3. 'choibk' user has permissions."
exit 1
fi
# 빈 파일 체크 (0 바이트면 실패로 간주)
if [ ! -s "${BACKUP_DIR}/${SQL_NAME}" ]; then
echo "[Error] Backup file is empty. Dump failed."
rm "${BACKUP_DIR}/${SQL_NAME}"
exit 1
fi
echo "[Success] All backups completed successfully."
# ==========================================
# 🚀 [STEP 2] 버전 동기화 및 코드 반영
# ==========================================
echo "[Step 2] Updating Source Code..."
cd "${PROJECT_DIR}"
# 목표 태그 설정
TARGET_TAG=$1
if [ -z "$TARGET_TAG" ]; then
echo " - Fetching latest tag info..."
git fetch origin --tags --force
TARGET_TAG=$(git describe --tags $(git rev-list --tags --max-count=1))
echo " - Detected latest tag: ${TARGET_TAG}"
fi
if [ -z "$TARGET_TAG" ]; then
echo "[Error] Target tag not found."
exit 1
fi
echo " - Syncing with remote..."
git fetch origin --tags --force --prune
if [ $? -ne 0 ]; then echo "[Error] Git fetch failed."; exit 1; fi
echo " - Checkout to ${TARGET_TAG}..."
git checkout -f "${TARGET_TAG}"
if [ $? -ne 0 ]; then echo "[Error] Git checkout failed."; exit 1; fi
# ==========================================
# 🏗️ [STEP 3] 시스템 빌드 및 서비스 재시작
# ==========================================
echo "[Step 3] Building and Restarting..."
# 3-1. 프론트엔드
echo " - Building Frontend..."
cd "${PROJECT_DIR}"
npm install --no-audit --no-fund > /dev/null
npm run build
# 3-2. 백엔드
echo " - Installing Backend Dependencies..."
cd "${SERVER_DIR}"
npm install --no-audit --no-fund > /dev/null
echo " - Reloading PM2..."
pm2 reload smartims-api || pm2 start index.js --name "smartims-api"
echo "=============================================="
echo "[Update] Completed Successfully at $(date)"
echo "[Info] Target Version: ${TARGET_TAG}"
echo "=============================================="