deploy.sh 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env bash
  2. # deploy.sh — chạy trên Pi 4 khi nhận webhook từ Gogs
  3. # Credentials đọc từ /opt/timelapse/.env (KHÔNG commit .env lên git)
  4. set -euo pipefail
  5. APP_DIR="${APP_DIR:-/opt/timelapse}"
  6. BRANCH="${1:-main}"
  7. # Load env vars từ local file (không có trong git)
  8. ENV_FILE="$APP_DIR/.env"
  9. if [[ -f "$ENV_FILE" ]]; then
  10. set -a
  11. source "$ENV_FILE"
  12. set +a
  13. fi
  14. log() { echo "[$(date '+%H:%M:%S')] $*"; }
  15. # Build authenticated git URL nếu có Gogs token
  16. REPO_URL="${GOGS_REPO_URL:-https://git.k9tech.space/kingkong/timelapse-2.git}"
  17. if [[ -n "${GOGS_TOKEN:-}" ]]; then
  18. REPO_URL="${REPO_URL/https:\/\//https://${GOGS_TOKEN}@}"
  19. fi
  20. deploy() {
  21. log "Deploying from $REPO_URL (branch: $BRANCH)"
  22. mkdir -p "$(dirname "$APP_DIR")"
  23. if [[ -d "$APP_DIR/.git" ]]; then
  24. cd "$APP_DIR"
  25. git remote set-url origin "$REPO_URL"
  26. git fetch origin
  27. git checkout "$BRANCH"
  28. git pull origin "$BRANCH"
  29. else
  30. log "Cloning fresh..."
  31. git clone --branch "$BRANCH" "$REPO_URL" "$APP_DIR"
  32. fi
  33. log "Installing deps..."
  34. cd "$APP_DIR"
  35. npm install --workspaces --include-workspace-root --ignore-scripts
  36. log "Building..."
  37. npm run build --workspace=packages/shared-types
  38. npm run build --workspace=apps/api-server
  39. npm run build --workspace=apps/web-dashboard
  40. log "Running migrations..."
  41. npm run migrate --workspace=apps/api-server || log "Migration skipped (no DB or error)"
  42. log "Restarting Docker Compose..."
  43. cd "$APP_DIR"
  44. docker compose down
  45. docker compose up -d --build postgres redis
  46. sleep 8
  47. docker compose up -d api-server web-dashboard worker || log "Some services skipped"
  48. log "Deploy complete!"
  49. }
  50. deploy