#!/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}"

LOCAL_APP_DIR="${LOCAL_APP_DIR:-/app}"

# 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 "$LOCAL_APP_DIR/.env.gitbucket" ]; then
        source "$LOCAL_APP_DIR/.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."
                # Strip potential carriage returns
                HOST=$(echo "$HOST" | tr -d '\r')
                USER=$(echo "$USER" | tr -d '\r')
                PASS=$(echo "$PASS" | tr -d '\r')
            fi
        else
            echo "Failed to fetch secrets from GitBucket."
        fi
        rm -rf "$TMP_SECRETS"
    fi
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..."
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # Check if brew exists
        if command -v brew &> /dev/null; then
            brew install sshpass
        elif [ -f "/opt/homebrew/bin/brew" ]; then
            /opt/homebrew/bin/brew install sshpass
        else
            echo "Error: Homebrew not found. Please install sshpass manually."
            exit 1
        fi
    else
        sudo apt-get update && sudo apt-get install -y sshpass
    fi
fi

# 1. Sync local codebase to temporary directory on remote server
echo "Syncing local files to production [USER: $USER, HOST: $HOST]..."
sshpass -p "$PASS" rsync -avz --delete \
  --exclude '.git' \
  --exclude 'node_modules' \
  --exclude 'frontend/node_modules' \
  --exclude 'frontend/build' \
  --exclude 'ai-hub/__pycache__' \
  --exclude '.venv' \
  --exclude 'cortex-ai*' \
  --exclude 'test_venv' \
  --exclude 'ai-hub/venv_pytest' \
  --exclude '._test_venv' \
  --exclude 'agent-node/dist' \
  --exclude 'data/' \
  --exclude 'data_old*' \
  --exclude 'CaudeCodeSourceCode/' \
  --exclude 'ai-hub-dump.db' \
  --exclude '*.log' \
  --exclude '.DS_Store' \
  --exclude '.env*' \
  --exclude '*.db' \
  --exclude '*.db-journal' \
  --exclude '*.db-wal' \
  --exclude '*.db-shm' \
  -e "ssh -o StrictHostKeyChecking=no" "$LOCAL_APP_DIR/" "$USER@$HOST:$REMOTE_TMP"

if [ $? -ne 0 ]; then
    echo "Rsync failed! Exiting."
    exit 1
fi

# 2. Sync from the temporary directory to the actual project directory
echo "Overwriting production project files..."
sshpass -p "$PASS" ssh -o StrictHostKeyChecking=no "$USER@$HOST" << EOF
  echo '$PASS' | sudo -S rsync -av --delete \
    --exclude 'data/' \
    --exclude '.env*' \
    --exclude 'agent-node/dist/' \
    --exclude 'CaudeCodeSourceCode/' \
    ${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 scripts/local_rebuild.sh $@
EOF

echo "Done! The new code is deployed to $HOST."
