#!/bin/bash

set -u

WINBOX_VERSION="4.4"
WINBOX_URL="https://download.mikrotik.com/routeros/winbox/4.4/WinBox_Linux.zip"

INSTALL_DIR="$HOME/.local/share/MikroTik/Winbox4"
WINBOX="$INSTALL_DIR/WinBox"

TMP_DIR=$(mktemp -d)

cleanup()
{
    rm -rf "$TMP_DIR"
}

trap cleanup EXIT

echo "Installing MikroTik WinBox ${WINBOX_VERSION}..."

# Проверяем наличие unzip
if ! command -v unzip >/dev/null 2>&1; then
    echo "Error: unzip is not installed."
    echo
    echo "Install it with:"
    echo "  openSUSE: sudo zypper install unzip"
    echo "  Debian:   sudo apt install unzip"
    exit 1
fi

# Проверяем wget/curl
if command -v wget >/dev/null 2>&1; then
    DOWNLOAD_CMD="wget"
elif command -v curl >/dev/null 2>&1; then
    DOWNLOAD_CMD="curl"
else
    echo "Error: neither wget nor curl is installed."
    exit 1
fi

# Создаём каталог установки
mkdir -p "$INSTALL_DIR" || {
    echo "Error: cannot create:"
    echo "$INSTALL_DIR"
    exit 1
}

ARCHIVE="$TMP_DIR/WinBox_Linux.zip"
EXTRACT_DIR="$TMP_DIR/extracted"

mkdir -p "$EXTRACT_DIR"

echo "Downloading WinBox ${WINBOX_VERSION}..."
echo "$WINBOX_URL"
echo

if [ "$DOWNLOAD_CMD" = "wget" ]; then
    wget -O "$ARCHIVE" "$WINBOX_URL" || {
        echo "Error: failed to download WinBox."
        exit 1
    }
else
    curl -L --fail --show-error -o "$ARCHIVE" "$WINBOX_URL" || {
        echo "Error: failed to download WinBox."
        exit 1
    }
fi

# Проверяем архив
if [ ! -s "$ARCHIVE" ]; then
    echo "Error: downloaded archive is empty."
    exit 1
fi

echo "Extracting archive..."

if ! unzip -q "$ARCHIVE" -d "$EXTRACT_DIR"; then
    echo "Error: failed to extract WinBox archive."
    exit 1
fi

# Ищем исполняемый файл WinBox
FOUND_WINBOX=$(find "$EXTRACT_DIR" -type f -name "WinBox" -print -quit)

if [ -z "$FOUND_WINBOX" ]; then
    echo "Error: executable 'WinBox' was not found in archive."
    echo
    echo "Archive contents:"
    find "$EXTRACT_DIR" -type f -print
    exit 1
fi

echo "Found:"
echo "$FOUND_WINBOX"

# Устанавливаем WinBox
if ! cp "$FOUND_WINBOX" "$WINBOX"; then
    echo "Error: failed to install WinBox."
    exit 1
fi

chmod +x "$WINBOX"

echo
echo "WinBox ${WINBOX_VERSION} installed successfully:"
echo "$WINBOX"
echo

# Запускаем WinBox
exec "$WINBOX" "$@"
