#!/bin/bash
# Description: Automates deployment from the local environment to the production host 192.168.68.113
# Credentials - Can be set via ENV or fetched from GitBucket
HOST="${REMOTE_HOST}"
USER="${REMOTE_USER}"
PASS="${REMOTE_PASS}"
# If credentials are missing, try to fetch from GitBucket Private Snippet
if [ -z "$PASS" ] || [ -z "$HOST" ]; then
# Load token/id from local env if present
if [ -f "/app/.env.gitbucket" ]; then
source "/app/.env.gitbucket"
fi
GITBUCKET_TOKEN="${GITBUCKET_TOKEN}"
SNIPPET_ID="${DEPLOYMENT_SNIPPET_ID}"
if [ -n "$GITBUCKET_TOKEN" ] && [ -n "$SNIPPET_ID" ]; then
echo "Secrets not provided in environment. Attempting to fetch from GitBucket..."
TMP_SECRETS=$(mktemp -d)
if git clone "https://yangyangxie:${GITBUCKET_TOKEN}@gitbucket.jerxie.com/git/gist/yangyangxie/${SNIPPET_ID}.git" "$TMP_SECRETS" &> /dev/null; then
if [ -f "$TMP_SECRETS/.env.production" ]; then
source "$TMP_SECRETS/.env.production"
HOST="${REMOTE_HOST:-$HOST}"
USER="${REMOTE_USER:-$USER}"
PASS="${REMOTE_PASSWORD:-$PASS}"
echo "Successfully loaded credentials from GitBucket."
fi
else
echo "Failed to fetch secrets from GitBucket."
fi
rm -rf "$TMP_SECRETS"
fi
# Fallback defaults if still not set
HOST="${HOST:-192.168.68.113}"
USER="${USER:-axieyangb}"
# System Paths
REMOTE_TMP="/tmp/cortex-hub/"
REMOTE_PROJ="/home/coder/project/cortex-hub"
if [ -z "$PASS" ]; then
echo "Error: REMOTE_PASS not found and could not be fetched from GitBucket."
echo "Please set REMOTE_PASS or GITBUCKET_TOKEN environment variables."
exit 1
fi
echo "Checking if sshpass is installed..."
if ! command -v sshpass &> /dev/null; then
echo "sshpass could not be found, installing..."
sudo apt-get update && sudo apt-get install -y sshpass
fi
# 1. Sync local codebase to temporary directory on remote server
echo "Syncing local files to production..."
sshpass -p "$PASS" rsync -avz \
--exclude '.git' \
--exclude 'node_modules' \
--exclude 'ui/client-app/node_modules' \
--exclude 'ui/client-app/build' \
--exclude 'ai-hub/__pycache__' \
--exclude '.venv' \
-e "ssh -o StrictHostKeyChecking=no" /app/ "$USER@$HOST:$REMOTE_TMP"
if [ $? -ne 0 ]; then
echo "Rsync failed! Exiting."
exit 1
fi
# 2. Copy the synced files into the actual project directory replacing the old ones
echo "Overwriting production project files..."
sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$USER@$HOST" << EOF
echo '$PASS' | sudo -S rm -rf $REMOTE_PROJ/nginx.conf
echo '$PASS' | sudo -S cp -r ${REMOTE_TMP}* $REMOTE_PROJ/
echo '$PASS' | sudo -S chown -R $USER:$USER $REMOTE_PROJ
EOF
# 3. Rebuild and restart services remotely
echo "Deploying on production server..."
sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$USER@$HOST" << EOF
cd $REMOTE_PROJ
echo '$PASS' | sudo -S bash deploy_local.sh
EOF
echo "Done! The new code is deployed to $HOST."
echo "CRITICAL: Run the automated Frontend Health Check now to verify production stability."
echo "Command: /frontend_tester"