#!/bin/bash

# This script is used to sync a project from
# a remote server to a local machine.

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

# Get current script real directory (follow symlinks)
SCRIPT_PATH="$(realpath "$0")"
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
ARCHIVE_NAME="sync.tar.gz"

# SSH options - auto-accept new host keys
SSH_OPTS="-o StrictHostKeyChecking=accept-new"

# Parse command line arguments
SFTP_ONLY=false
FILES_ONLY=false

for arg in "$@"; do
    case "$arg" in
        -h|--help)
            cat "$SCRIPT_DIR/MANUAL"
            exit 0
            ;;
        --sftp-only)
            SFTP_ONLY=true
            echo -e "${YELLOW}SFTP only mode enabled${NC}"
            ;;
        --files-only)
            FILES_ONLY=true
            echo -e "${YELLOW}Files only mode enabled${NC}"
            ;;
    esac
done

# Function to add entry to .gitignore if not already present
add_to_gitignore() {
    local entry="$1"
    cat .gitignore | grep "$entry" > /dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "$entry" >> .gitignore
        echo -e "${BLUE}Added $entry to .gitignore${NC}"
    else
        echo -e "${YELLOW}$entry already is inside of .gitignore file${NC}"
    fi
}

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

# Check if config is predefined (for testing usually)
if [ -f ".sync-credentials" ]; then
    source ".sync-credentials"
else
    # Prompt for configuration (password before path for SSH resolution)
    read -p "Server user@host (e.g., leo@server.com): " SERVER_HOST
    read -sp "SSH Password: " SSH_PASSWORD
    echo ""
    read -p "Server project path (default: ~/public_leo): " SERVER_PROJECT_PATH
    read -p "Local folder path (e.g., Delta Pharmacy): " LOCAL_FOLDER
    echo ""
fi

# Default path to ~/public_leo if empty
if [ -z "$SERVER_PROJECT_PATH" ]; then
    SERVER_PROJECT_PATH="~/public_leo"
fi

# Resolve ~ to full path via SSH
if [[ "$SERVER_PROJECT_PATH" == ~* ]]; then
    echo "Resolving path..."
    SERVER_PROJECT_PATH=$(sshpass -p "${SSH_PASSWORD}" ssh $SSH_OPTS ${SERVER_HOST} "cd ${SERVER_PROJECT_PATH} && pwd")
    if [ $? -ne 0 ]; then
        echo -e "${RED}Failed to resolve path${NC}"
        exit 1
    fi
    echo -e "${GREEN}Resolved to: ${SERVER_PROJECT_PATH}${NC}"
fi

# Validate required variables (all except password)
if [ -z "$SERVER_HOST" ]; then
    echo -e "${RED}Error: SERVER_HOST is not set${NC}"
    exit 1
fi

if [ -z "$SERVER_PROJECT_PATH" ]; then
    echo -e "${RED}Error: SERVER_PROJECT_PATH is not set${NC}"
    exit 1
fi

if [ -z "$LOCAL_FOLDER" ]; then
    echo -e "${RED}Error: LOCAL_FOLDER is not set${NC}"
    exit 1
fi

# Sync terminal info on full sync (no flags)
if [ "$SFTP_ONLY" = false ] && [ "$FILES_ONLY" = false ]; then
    # Detect terminal type
    if [[ "$TERM" == *"ghostty"* ]]; then
        TERM_TYPE="xterm-ghostty"
    elif [[ "$TERM" == *"kitty"* ]]; then
        TERM_TYPE="xterm-kitty"
    else
        TERM_TYPE=""
    fi

    if [ -n "$TERM_TYPE" ]; then
        echo "Syncing terminal info ($TERM_TYPE)..."
        infocmp -x "$TERM_TYPE" | sshpass -p "${SSH_PASSWORD}" ssh $SSH_OPTS ${SERVER_HOST} -- tic -x -
        echo -e "${GREEN}Terminal info synced${NC}"
    else
        echo -e "${YELLOW}Warning: Unknown terminal ($TERM), skipping terminfo sync${NC}"
    fi
fi

# Start sync process
echo "Starting project sync..."

# Step 1: SSH into server and create tar archive
echo "Creating archive on server..."
if [ "$FILES_ONLY" = true ]; then
    sshpass -p "${SSH_PASSWORD}" ssh $SSH_OPTS ${SERVER_HOST} "cd ${SERVER_PROJECT_PATH} && tar -czf ../${ARCHIVE_NAME} --exclude='node_modules' --exclude='vendor' ."
else
    sshpass -p "${SSH_PASSWORD}" ssh $SSH_OPTS ${SERVER_HOST} "cd ${SERVER_PROJECT_PATH} && tar -czf ../${ARCHIVE_NAME} ."
fi

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 $SSH_OPTS ${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 $SSH_OPTS ${SERVER_HOST} "rm ~/${ARCHIVE_NAME}"

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

# Skip helper scripts and config generation in files-only mode
if [ "$FILES_ONLY" = true ]; then
    exit 0
fi

# 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
if [ "$SFTP_ONLY" = true ]; then
	# Sftp only scripts
    scripts=("local-remote.sh" "remote-local.sh" "sftp-watch.sh" "ssh.sh")
else
	# All scripts
    scripts=("watch-build.sh" "local-remote.sh" "remote-local.sh" "sftp-watch.sh" "ssh.sh" "split-conflicts.sh")
fi

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}/\"
    REMOTE_PROGRESS=\".remote-in-progress\"
    " > "${script}"

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

    # Skip .gitignore updates when --sftp-only flag is present
    if [ "$SFTP_ONLY" = false ]; then
        add_to_gitignore "${script}"
    fi
done

# Upload lazygit to server (skip when --sftp-only flag is present)
if [ "$SFTP_ONLY" = false ]; then
    echo "Uploading lazygit to server..."

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

    # Add lazygit to .gitignore
    add_to_gitignore "lazygit"
fi
