#!/bin/bash

# Define deployment variables
SERVER_USER="cyarsflu"
SERVER_IP="cyaren.com"
SERVER_SSH_PORT="21098"
DEPLOY_PATH="/home/cyarsflu/nodejs_app"
PUBLIC_HTML_PATH="/home/cyarsflu/public_html"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Create temporary deployment directory with structure
echo "Creating deploy-temp directory structure..."
mkdir -p deploy-temp/{public,src}

# Copy React build files to deploy-temp
echo "Copying React build files to deploy-temp..."
cp -r "$SCRIPT_DIR/../build"/* deploy-temp/public/

# Copy Node.js server files to deploy-temp, excluding .env files
echo "Copying Node.js server files with .env exclusion..."
cd "$SCRIPT_DIR/../server"
rsync -av --exclude='.env*' --exclude='node_modules/' --exclude='tmp/' --exclude='deploy-temp/' ./ "$SCRIPT_DIR/deploy-temp/src/"

# Deploy Node.js server files to $DEPLOY_PATH
echo "Deploying Node.js server files to $DEPLOY_PATH..."
cd "$SCRIPT_DIR"
sftp -P $SERVER_SSH_PORT $SERVER_USER@$SERVER_IP <<EOF
cd $DEPLOY_PATH
rm -rf src/*  # Clear out old server files
put -r deploy-temp/src/*
EOF

# Deploy React build files to $PUBLIC_HTML_PATH
echo "Deploying React build files to $PUBLIC_HTML_PATH..."
sftp -P $SERVER_SSH_PORT $SERVER_USER@$SERVER_IP <<EOF
cd $PUBLIC_HTML_PATH
rm -rf *  # Clear out old static files
put -r deploy-temp/public/*
EOF

# Clean up the temporary directory
echo "Cleaning up temporary directory..."
rm -rf deploy-temp

echo "Deployment completed."
