#!/bin/bash

# This script is used to sync a project from
# a remote server to a local machine.
#
# Considerations:
# 1. The server must have an SSH key set up for password-less login.
# 2. The server must have the project files in a specific folder. (~/public_leo, etc..)
#
# How it works:
# 1. created an archive on the server
# 2. copy the archive to the local machine
# 3. extract the archive locally
# 4. delete the local archive
# 5. delete the server archive
# 6. create .vscode/sftp.json file

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Get current script real directory (follow symlinks)
SCRIPT_PATH="$(realpath "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"

echo -e "${BLUE}=== Project Sync Configuration ===${NC}"
echo ""

# Prompt for configuration
read -p "Server user@host (e.g., leo@server.com): " SERVER_HOST
read -p "Server project path (e.g., /home/leo/public_leo): " SERVER_PROJECT_PATH
read -p "Local folder path (e.g., Delta Pharmacy): " LOCAL_FOLDER
read -sp "SSH Password: " SSH_PASSWORD
echo ""
echo ""

ARCHIVE_NAME="leo.tar.gz"

echo "Starting project sync..."

# Step 1: SSH into server and create tar archive
echo "Creating archive on server..."
sshpass -p "${SSH_PASSWORD}" ssh ${SERVER_HOST} "cd ${SERVER_PROJECT_PATH} && tar -czf ../${ARCHIVE_NAME} ."

if [ $? -ne 0 ]; then
    echo -e "${RED}Failed to create archive on server${NC}"
    exit 1
fi

echo -e "${GREEN}Archive created successfully${NC}"

# Step 2: Create local folder if it doesn't exist
mkdir -p "${LOCAL_FOLDER}"

# Step 3: Copy archive from server to local
echo "Copying archive to local machine..."
sshpass -p "${SSH_PASSWORD}" scp ${SERVER_HOST}:~/${ARCHIVE_NAME} "${LOCAL_FOLDER}/"

if [ $? -ne 0 ]; then
    echo -e "${RED}Failed to copy archive${NC}"
    exit 1
fi

echo -e "${GREEN}Archive copied successfully${NC}"

# Step 4: Extract archive locally
echo "Extracting archive..."
cd "${LOCAL_FOLDER}"
tar -xzf ${ARCHIVE_NAME}

if [ $? -ne 0 ]; then
    echo -e "${RED}Failed to extract archive${NC}"
    exit 1
fi

echo -e "${GREEN}Archive extracted successfully${NC}"

# Step 5: Clean up - delete local archive
echo "Cleaning up local archive..."
rm ${ARCHIVE_NAME}

# Step 6: Clean up - delete server archive
echo "Cleaning up server archive..."
sshpass -p "${SSH_PASSWORD}" ssh ${SERVER_HOST} "rm ~/${ARCHIVE_NAME}"

echo -e "${GREEN}File sync complete!${NC}"

# Create .vscode sftp.json file
mkdir -p .vscode

# Extract username and host from SERVER_HOST
USERNAME="${SERVER_HOST%@*}"
HOST="${SERVER_HOST#*@}"

echo "{
  \"name\": \"${LOCAL_FOLDER}\",
  \"host\": \"${HOST}\",
  \"protocol\": \"sftp\",
  \"port\": 22,
  \"username\": \"${USERNAME}\",
  \"password\": \"${SSH_PASSWORD}\",
  \"remotePath\": \"${SERVER_PROJECT_PATH}\",
  \"uploadOnSave\": true,
  \"useTempFile\": false,
  \"openSsh\": false,
  \"ignore\": [
    \".vscode\",
    \".DS_Store\",
    \"node_modules\",
    \"vendor\",
    \"storage\",
    \"uploads\",
    \"temp\",
    \"cache\",
    \"sitepress-multilingual-cms\"
  ]
}" >.vscode/sftp.json

echo -e "${GREEN}.vscode/sftp.json created successfully${NC}"

# Go through scripts, add variables and add them to project folder
scripts=("build-watch.sh" "local-remote.sh" "remote-local.sh" "sftp-watch.sh")

for script in "${scripts[@]}"; do
    # Add variables to script
    echo "
    #!/bin/bash
    set -e

    # Configuration
    SERVER_USER=\"${USERNAME}\"
    SERVER_HOST=\"${HOST}\"
    SERVER_PASSWORD=\"${SSH_PASSWORD}\"
    SERVER_PATH=\"${SERVER_PROJECT_PATH}/\"
    " > "${script}"

    # Append the rest of the upload core build script
    cat "${SCRIPT_DIR}/scripts/${script}" >> "${script}"
    echo "${script} created successfully"

    # Add script to .gitignore
    echo "${script}" >> .gitignore
    echo -e "${BLUE}Added ${script} to .gitignore${NC}"
done

# Upload lazygit to server
echo "Uploading lazygit to server..."

cp "${SCRIPT_DIR}/lazygit" .
sshpass -p "${SSH_PASSWORD}" scp "${SCRIPT_DIR}/lazygit" ${SERVER_HOST}:${SERVER_PROJECT_PATH}
echo -e "${GREEN}lazygit uploaded successfully${NC}"

# Add lazygit to .gitignore
echo "lazygit" >> .gitignore
echo -e "${BLUE}Added lazygit to .gitignore${NC}"
