#!/bin/bash
#version_1.2
echo "Checking MinIO Client..."
if command -v minio-client &> /dev/null; then
    echo "MinIO Client installed."
else
    echo "Installing MinIO Client..."

    wget https://dl.min.io/client/mc/release/linux-amd64/mc

    chmod +x mc

    sudo mv mc /usr/local/bin/minio-client
    echo "MinIO Client installed."
fi

if [ "$#" -ne 1 ]; then
    echo "Usage: $0 {dump|restore}"
    exit 1
fi

set_minio_alias() {
    
    local ip="$1"
    local access="$2"
    local secret="$3"

    output=$(minio-client alias set myminio http://$ip:9000 $access $secret 2>&1)

    if [[ $? -eq 0 ]]; then
        echo "Alias successfully set."
    else
        if echo "$output" | grep -q "Check your key and signing method."; then
            echo "Key error: Please check your access keys."
        elif echo "$output" | grep -q "Invalid arguments provided"; then
            echo "Key error: Please check your access keys."
        elif echo "$output" | grep -q "connection refused"; then
            echo "Connection error: Please check if the MinIO server is running and the IP address is correct."
        elif echo "$output" | grep -q "no such host"; then
            echo "Connection error: Please check if the MinIO server is running and the IP address is correct."
        else
            echo "An unknown error occurred."
            echo "Output: $output"
        fi
        exit 1
    fi

    return 0
}

complete_dir() {
    local dir
    dir="${COMP_WORDS[COMP_CWORD]}"
    COMPREPLY=($(compgen -d -- "$dir"))
}
complete -F complete_dir elph-chat-backup.sh

case "$1" in
    dump)
    #minio
 
    access=""
    while [[ -z "$access" ]]; do
        read -p "Enter MinIO access key: " access
        if [[ -z "$access" ]]; then
            echo "Error: value cannot be empty. Please try again."
        fi
    done

    secret=""
    while [[ -z "$secret" ]]; do
        read -p "Enter MinIO secret key: " secret
        if [[ -z "$secret" ]]; then
            echo "Error: value cannot be empty. Please try again."
        fi
    done
    
    ip=""
    while [[ -z "$ip" ]]; do
        read -p "Enter MinIO ip or domain(Example: elph-chat-server.loc): " ip
        if [[ -z "$ip" ]]; then
            echo "Error: value cannot be empty. Please try again."
        fi
    done

    set_minio_alias "$ip" "$access" "$secret"

    #mongo
    mongo_container=$(docker ps --format '{{.Names}}'| grep 'mongo-1$')

    #start backup
    date=$(date '+%d.%m.%Y.%H:%M')

    default_backup_dir="$HOME/elph-chat-backups/$date/"
    backup_dir=""
    while true; do
        read -e -p "Enter backup directory or press enter to use default (Default: $default_backup_dir): " backup_dir

        if [[ -z "$backup_dir" ]]; then
            backup_dir="$default_backup_dir"
        fi
        
        if [[ "${backup_dir: -1}" != "/" ]]; then
            backup_dir="${backup_dir}/"
        fi

        if [[ ! -d "$backup_dir" ]]; then
            echo "Directory does not exist. Attempting to create directory: $backup_dir"
            mkdir -p "$backup_dir" 2>/dev/null
            
            if [[ $? -ne 0 ]]; then
                echo "Failed to create directory: $backup_dir. Please enter a different directory."
                continue
            fi
        elif [[ ! -w "$backup_dir" ]]; then
            echo "Directory exists but is not writable: $backup_dir"
            echo "Please enter a different directory."
            continue
        fi

        break
    done

    mkdir -p "$backup_dir"mongo
    mkdir -p "$backup_dir"minio
    
    echo "Starting mongo backup..."

    docker exec "$mongo_container" mongodump --archive > "$backup_dir"mongo/mongodump.gz

    echo "✅ Mongo backup ended. Check files in $backup_dir"

    echo "Starting MinIO backup..."

    if minio-client ls myminio/elph-chat | grep -q .; then
        minio-client cp --recursive myminio/elph-chat "$backup_dir"/minio
    else
        echo "Directory myminio/elph-chat is empty."
    fi

    if minio-client ls myminio/temp-files | grep -q .; then
        minio-client cp --recursive myminio/temp-files "$backup_dir"/minio
    else
        echo "Directory myminio/temp-files is empty."
    fi

    echo "✅ MinIO backup ended. Check files in $backup_dir"
        ;;
    restore)
    #minio
    access=""
    while [[ -z "$access" ]]; do
        read -p "Enter MinIO access key: " access
        if [[ -z "$access" ]]; then
            echo "Error: value cannot be empty. Please try again."
        fi
    done

    secret=""
    while [[ -z "$secret" ]]; do
        read -p "Enter MinIO secret key: " secret
        if [[ -z "$secret" ]]; then
            echo "Error: value cannot be empty. Please try again."
        fi
    done
    
    ip=""
    while [[ -z "$ip" ]]; do
        read -p "Enter MinIO ip or domain(Example: elph-chat-server.loc): " ip
        if [[ -z "$ip" ]]; then
            echo "Error: value cannot be empty. Please try again."
        fi
    done

    set_minio_alias "$ip" "$access" "$secret"

    #mongo
    mongo_container=$(docker ps --format '{{.Names}}'| grep 'mongo-1$')

    read -e -p "Enter backup directory: " dir_path

    if [ -d "$dir_path" ]; then

        if [ -d "$dir_path/mongo" ]; then
            echo "Starting mongo restore..."
            docker exec -i "$mongo_container" sh -c 'mongorestore --archive --db elph --drop' < "$dir_path"/mongo/mongodump.gz
            echo "✅ Mongo backup ended."
        else
            echo "Backup directory not contain /mongo"
        fi

        if [ -d "$dir_path/minio" ]; then
            echo "Starting MinIO restore..."
            minio-client alias set myminio http://$ip:9000 $access $secret

            if minio-client ls $dir_path/minio/elph-chat/rooms | grep -q .; then
                minio-client cp --recursive "$dir_path/minio/elph-chat/rooms" myminio/elph-chat/
            else
                echo "Directory myminio/elph-chat is empty."
            fi

            if minio-client ls $dir_path/minio/elph-chat/users | grep -q .; then
                minio-client cp --recursive "$dir_path/minio/elph-chat/users" myminio/elph-chat/
            else
                echo "Directory myminio/elph-chat is empty."
            fi

            if minio-client ls $dir_path/minio/temp-files | grep -q .; then
                minio-client cp --recursive  "$dir_path/minio/temp-files" myminio/temp-files
            else
                echo "Directory myminio/elph-chat is empty."
            fi
            echo "✅ MinIO restore ended ended"
        else
                echo "Backup directory not contain /minio"
        fi
    else
        echo "Error. Enter backup directory."
    fi

        ;;
    *)
        echo "Unknown command: $1"
        echo "Usage: $0 {dump|restore}"
        exit 1
        ;;
esac
