#!/bin/bash

# Enhance transfer script with SSH key setup
# Version 1.1 powered by JoneSolutions.Com

# Function to print section headers
print_header() {
    echo -e "\n\033[1;34m=== $1 ===\033[0m"
}

# Function to print status messages
print_status() {
    echo -e "\033[1;32m[*]\033[0m $1"
}

# Function to print error messages
print_error() {
    echo -e "\033[1;31m[!]\033[0m $1" >&2
}

# Function to generate SSH key if not exists
generate_ssh_key() {
    if [ ! -f ~/.ssh/id_rsa.pub ]; then
        print_header "Generating SSH Key"
        ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N "" -q
        if [ $? -eq 0 ]; then
            print_status "SSH key pair generated successfully"
        else
            print_error "Failed to generate SSH key pair"
            exit 1
        fi
    else
        print_status "Existing SSH key found (~/.ssh/id_rsa.pub)"
    fi
}

# Function to copy SSH key to target server
copy_ssh_key() {
    local target_ip=$1
    local password=$2
    
    print_header "Configuring SSH Key Authentication"
    if sshpass -p "$password" ssh-copy-id -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa.pub root@$target_ip; then
        print_status "SSH key successfully copied to $target_ip"
        return 0
    else
        print_error "Failed to copy SSH key to $target_ip"
        return 1
    fi
}

# Get target IP address
read -p "Enter target server IP address [9.9.9.9]: " TARGET_IP
TARGET_IP=${TARGET_IP:-9.9.9.9}

# Get root password
read -s -p "Enter root password for target server: " ROOT_PASSWORD
echo ""

# Generate and configure SSH key
generate_ssh_key
copy_ssh_key "$TARGET_IP" "$ROOT_PASSWORD"

# Verify SSH connection with key
print_header "Testing SSH Key Connection"
if ssh -o PasswordAuthentication=no -o StrictHostKeyChecking=no root@$TARGET_IP "echo 'SSH key authentication successful'"; then
    print_status "SSH key authentication working"
    USE_SSH_KEY=true
else
    print_error "SSH key authentication failed, falling back to password"
    USE_SSH_KEY=false
fi

# Stop and disable services
print_header "Stopping Local Services"
systemctl stop orchd && print_status "orchd stopped" || print_error "Failed to stop orchd"
systemctl stop appcd && print_status "appcd stopped" || print_error "Failed to stop appcd"
systemctl disable orchd && print_status "orchd disabled" || print_error "Failed to disable orchd"
systemctl disable appcd && print_status "appcd disabled" || print_error "Failed to disable appcd"

# Create database dumps
print_header "Creating Database Dumps"
sudo -u orchd pg_dump -O -d orchd > /var/orchd/orchd.sql && print_status "orchd.sql created" || print_error "Failed to create orchd.sql"
sudo -u orchd pg_dump -O -d authd > /var/orchd/authd.sql && print_status "authd.sql created" || print_error "Failed to create authd.sql"

# Transfer function that uses the most appropriate method
transfer_file() {
    local src=$1
    local dest=$2
    
    if [ "$USE_SSH_KEY" = true ]; then
        scp -o StrictHostKeyChecking=no -o PasswordAuthentication=no "$src" "$dest"
    else
        sshpass -p "$ROOT_PASSWORD" scp -o StrictHostKeyChecking=no "$src" "$dest"
    fi
}

# Transfer database files
print_header "Transferring Database Files"
transfer_file /var/orchd/orchd.sql root@$TARGET_IP:/var/orchd/orchd.sql && print_status "orchd.sql transferred" || print_error "Failed to transfer orchd.sql"
transfer_file /var/orchd/authd.sql root@$TARGET_IP:/var/orchd/authd.sql && print_status "authd.sql transferred" || print_error "Failed to transfer authd.sql"

# Transfer mTLS certificates
print_header "Transferring mTLS Certificates"
if [ "$USE_SSH_KEY" = true ]; then
    scp -o StrictHostKeyChecking=no -o PasswordAuthentication=no -r /etc/ssl/certs/enhance root@$TARGET_IP:/etc/ssl/certs/
else
    sshpass -p "$ROOT_PASSWORD" scp -o StrictHostKeyChecking=no -r /etc/ssl/certs/enhance root@$TARGET_IP:/etc/ssl/certs/
fi && print_status "Public certs transferred" || print_error "Failed to transfer public certs"

if [ "$USE_SSH_KEY" = true ]; then
    scp -o StrictHostKeyChecking=no -o PasswordAuthentication=no -r /etc/ssl/private/enhance root@$TARGET_IP:/etc/ssl/private/
else
    sshpass -p "$ROOT_PASSWORD" scp -o StrictHostKeyChecking=no -r /etc/ssl/private/enhance root@$TARGET_IP:/etc/ssl/private/
fi && print_status "Private certs transferred" || print_error "Failed to transfer private certs"

if [ "$USE_SSH_KEY" = true ]; then
    scp -o StrictHostKeyChecking=no -o PasswordAuthentication=no -r /var/local/enhance/orchd/private root@$TARGET_IP:/var/local/enhance/orchd/
else
    sshpass -p "$ROOT_PASSWORD" scp -o StrictHostKeyChecking=no -r /var/local/enhance/orchd/private root@$TARGET_IP:/var/local/enhance/orchd/
fi && print_status "ORCHD private files transferred" || print_error "Failed to transfer ORCHD private files"

transfer_file /var/local/enhance/rca.pw root@$TARGET_IP:/var/local/enhance/rca.pw && print_status "RCA password transferred" || print_error "Failed to transfer RCA password"

# Transfer control panel assets
print_header "Transferring Control Panel Assets"
if [ "$USE_SSH_KEY" = true ]; then
    scp -o StrictHostKeyChecking=no -o PasswordAuthentication=no -r /var/www/control-panel/assets root@$TARGET_IP:/var/www/control-panel/
else
    sshpass -p "$ROOT_PASSWORD" scp -o StrictHostKeyChecking=no -r /var/www/control-panel/assets root@$TARGET_IP:/var/www/control-panel/
fi && print_status "Control panel assets transferred" || print_error "Failed to transfer control panel assets"

# Transfer Cloudflare key (if exists)
if [ -f "/var/local/enhance/orchd/cloudflare.key" ]; then
    print_header "Transferring Cloudflare Key"
    transfer_file /var/local/enhance/orchd/cloudflare.key root@$TARGET_IP:/var/local/enhance/orchd/cloudflare.key && print_status "Cloudflare key transferred" || print_error "Failed to transfer Cloudflare key"
else
    print_status "No Cloudflare key found, skipping"
fi

print_header "Transfer Complete"
echo "All data has been successfully transferred to $TARGET_IP"
echo "Database files: /var/orchd/orchd.sql and /var/orchd/authd.sql"
echo "mTLS certificates transferred to:"
echo "  - /etc/ssl/certs/enhance/"
echo "  - /etc/ssl/private/enhance/"
echo "  - /var/local/enhance/orchd/private/"
echo "Control panel assets transferred to: /var/www/control-panel/assets/"
echo ""
echo "SSH key authentication configured: $USE_SSH_KEY"
if [ "$USE_SSH_KEY" = true ]; then
    echo "You can now connect without password using: ssh root@$TARGET_IP"
fi
