#!/bin/bash

# MiOS DOWL MANAGER for Linux
# Сохраните как: MiOS_DOWL_MANAGER.sh
# Сделайте исполняемым: chmod +x MiOS_DOWL_MANAGER.sh
# Запустите: ./MiOS_DOWL_MANAGER.sh

# Цвета для вывода
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Получаем путь к рабочему столу
DESKTOP="$HOME/Desktop"
if [ ! -d "$DESKTOP" ]; then
    DESKTOP="$HOME/Рабочий стол"
fi
if [ ! -d "$DESKTOP" ]; then
    DESKTOP="$HOME"
fi

# Функция для скачивания файлов
download_file() {
    local url="$1"
    local folder="$2"
    local filename="$3"
    
    # Создаем папку если её нет
    if [ ! -d "$folder" ]; then
        mkdir -p "$folder"
        echo -e "${GREEN}Created folder: $folder${NC}"
    fi
    
    local path="$folder/$filename"
    
    # Проверяем существует ли файл
    if [ -f "$path" ]; then
        echo -e "${YELLOW}File exists: $path${NC}"
        echo -n "Overwrite? (y/n): "
        read response
        if [[ "$response" != "y" && "$response" != "Y" ]]; then
            echo -e "${YELLOW}Cancelled.${NC}"
            return
        fi
    fi
    
    echo -e "${BLUE}Downloading $filename...${NC}"
    echo "Saving to: $path"
    
    # Используем wget или curl
    if command -v wget &> /dev/null; then
        if wget -q --show-progress "$url" -O "$path"; then
            echo -e "${GREEN}Download completed!${NC}"
        else
            echo -e "${RED}Error: Download failed${NC}"
            return
        fi
    elif command -v curl &> /dev/null; then
        if curl -# -L "$url" -o "$path"; then
            echo -e "${GREEN}Download completed!${NC}"
        else
            echo -e "${RED}Error: Download failed${NC}"
            return
        fi
    else
        echo -e "${RED}Error: Neither wget nor curl found. Please install one of them.${NC}"
        return
    fi
    
    # Показываем размер файла
    if [ -f "$path" ]; then
        size=$(du -h "$path" | cut -f1)
        echo "Size: $size"
    fi
}

# Очищаем экран
clear

# Заголовок
echo -e "${BLUE}MiOS DOWL MANAGER${NC}"
echo -e "${GREEN}connect server... [OK]${NC}"
echo ""

# Основной цикл
while true; do
    echo -n "> "
    read input
    
    # Пропускаем пустой ввод
    if [ -z "$input" ]; then
        continue
    fi
    
    # Разбиваем команду
    cmd=($input)
    
    # Обработка команд
    case "${cmd[0],,}" in
        "os")
            if [ "${#cmd[@]}" -ge 3 ] && [[ "${cmd[1],,}" == "/dowl" ]]; then
                if [[ "${cmd[2],,}" == "mios.iso" ]]; then
                    download_file "https://mios-server-dowl.vercel.app/MiOS/MiOS.iso" \
                                 "$DESKTOP/os_iso" "MiOS.iso"
                else
                    echo "Unknown file. Use: os /dowl mios.iso"
                fi
            else
                echo "Usage: os /dowl mios.iso"
            fi
            ;;
            
        "source")
            if [ "${#cmd[@]}" -ge 2 ] && [[ "${cmd[1],,}" == "/dowl" ]]; then
                echo -e "${BLUE}Opening browser...${NC}"
                if command -v xdg-open &> /dev/null; then
                    xdg-open "https://archive.org/details/source_code_202607"
                    echo -e "${GREEN}Browser opened!${NC}"
                elif command -v gnome-open &> /dev/null; then
                    gnome-open "https://archive.org/details/source_code_202607"
                    echo -e "${GREEN}Browser opened!${NC}"
                elif command -v open &> /dev/null; then
                    open "https://archive.org/details/source_code_202607"
                    echo -e "${GREEN}Browser opened!${NC}"
                else
                    echo -e "${RED}Error: Could not open browser. Please open manually:${NC}"
                    echo "https://archive.org/details/source_code_202607"
                fi
            else
                echo "Usage: source /dowl"
            fi
            ;;
            
        "fat")
            if [ "${#cmd[@]}" -ge 2 ] && [[ "${cmd[1],,}" == "/dowl" ]]; then
                download_file "https://mios-server-dowl.vercel.app/FAT_IMAGE/fat32.img" \
                             "$DESKTOP/fat_image" "fat32.img"
            else
                echo "Usage: fat /dowl"
            fi
            ;;
            
        "exit"|"quit")
            echo "Goodbye!"
            break
            ;;
            
        "help")
            echo "Commands:"
            echo "  os /dowl mios.iso  - Download MiOS ISO"
            echo "  source /dowl       - Open source code in browser"
            echo "  fat /dowl          - Download FAT32 image"
            echo "  exit, quit         - Exit program"
            echo "  help               - Show this help"
            ;;
            
        *)
            echo "Unknown command. Type 'help'"
            ;;
    esac
done