#!/bin/bash

if [ "$EUID" -ne 0 ]; then
    echo "Please run as root (sudo)"
    exit 1
fi

# Lang messages
if echo "$LANG" | grep -q "ru"; then
    TITLE="Настраивается r7draw"
    MSG_API_URL="Укажите полный URL-адрес к Р7-Диск. Этот адрес используется для интеграции с Р7-Диск и совместной работы.\n\nURL:"
    MSG_DOMAIN="Укажите домен, на котором работает Р7-Диск. Это необходимо для корректной работы Cookie.\n\nДомен:"
    MSG_HTTPS="Включить доступ к сайту через протокол HTTPS.\n\nИспользовать HTTPS?"
    MSG_CERT="Укажите файл сертификата.\n\nФайл:"
    MSG_KEY="Укажите файл ключа сертификата.\n\nФайл:"
    MSG_ERR_FILE="Файл не найден.\n\nУказанный путь не существует. Пожалуйста, введите корректный путь к файлу."
    BTN_CANCEL="Отмена"
    MSG_CANCEL="Установка прервана пользователем."
    ERR_PKG="Ошибка. Не найден подходящий пакетный менеджер (dnf или apt-get)"
    ERR_ARCH="Ошибка. Неподдерживаемая архитектура:"
else
    TITLE="Configuring r7draw"
    MSG_API_URL="Specify the full URL to access the R7-Disk.\n\nURL:"
    MSG_DOMAIN="Specify the domain where R7-Disk is running. This is required for Cookies.\n\nDomain:"
    MSG_HTTPS="Enable site access via HTTPS.\n\nUse HTTPS?"
    MSG_CERT="Specify the certificate file.\n\nFile:"
    MSG_KEY="Specify the certificate key file.\n\nFile:"
    MSG_ERR_FILE="File not found.\n\nThe specified path does not exist. Please enter a valid path to the file."
    BTN_CANCEL="Cancel"
    MSG_CANCEL="Installation aborted by user."
    ERR_PKG="Error. Suitable package manager not found (dnf or apt-get)"
    ERR_ARCH="Error. Unsupported architecture:"
fi

# Check and try install whiptail (GUI)
if command -v dnf &> /dev/null; then
    PKG_MANAGER="dnf"
    if ! command -v whiptail &> /dev/null; then
        dnf install -y newt
    fi
elif command -v apt-get &> /dev/null; then
    PKG_MANAGER="apt-get"
    if ! command -v whiptail &> /dev/null; then
        apt-get update
        apt-get install -y newt52
    fi
else
    echo "$ERR_PKG"
    exit 1
fi

# Read parameters
in_api_url=$(whiptail --title "$TITLE" --ok-button "Ok" --cancel-button "$BTN_CANCEL" --inputbox "$MSG_API_URL" 10 110 "https://disk.example.com" 3>&1 1>&2 2>&3)
if [ $? -ne 0 ]; then
    echo "$MSG_CANCEL"
    exit 1
fi
if ! [ $? = 0 ] || [ -z "$in_api_url" ]; then
    in_api_url="https://disk.example.com"
fi

in_domain=$(whiptail --title "$TITLE" --ok-button "Ok" --cancel-button "$BTN_CANCEL" --inputbox "$MSG_DOMAIN" 10 95 "example.com" 3>&1 1>&2 2>&3)
if [ $? -ne 0 ]; then
    echo "$MSG_CANCEL"
    exit 1
fi
if ! [ $? = 0 ] || [ -z "$in_domain" ]; then
    in_domain="example.com"
fi

is_https="false"
if (whiptail --title "$TITLE" --yesno "$MSG_HTTPS" 10 50); then
    is_https="true"

    while true; do
        in_cert=$(whiptail --title "$TITLE" --ok-button "Ok" --cancel-button "$BTN_CANCEL" --inputbox "$MSG_CERT" 10 50 "/etc/nginx/ssl/r7draw.crt" 3>&1 1>&2 2>&3)
        [ $? -ne 0 ] && { echo "$MSG_CANCEL"; exit 1; }
        
        if [ -f "$in_cert" ]; then
            break
        else
            whiptail --title "$TITLE" --msgbox "$MSG_ERR_FILE" 10 80
        fi
    done

    while true; do
        in_cert_key=$(whiptail --title "$TITLE" --ok-button "Ok" --cancel-button "$BTN_CANCEL" --inputbox "$MSG_KEY" 10 50 "/etc/nginx/ssl/r7draw.key" 3>&1 1>&2 2>&3)
        [ $? -ne 0 ] && { echo "$MSG_CANCEL"; exit 1; }

        if [ -f "$in_cert_key" ]; then
            break
        else
            whiptail --title "$TITLE" --msgbox "$MSG_ERR_FILE" 10 80
        fi
    done
fi

# Install
export API_URL="$in_api_url"
export DOMAIN="$in_domain"
export MAKE_HTTPS="$is_https"
export CERTIFICATE="$in_cert"
export CERTIFICATE_KEY="$in_cert_key"

ARCH=$(uname -m)

if [ "$ARCH" == "x86_64" ] || [ "$ARCH" == "aarch64" ]; then
    if [ "$PKG_MANAGER" == "dnf" ]; then
        dnf install -y ./r7draw-*.$ARCH.rpm
    else
        apt-get install -y ./r7draw-*.$ARCH.rpm
    fi
else
    echo "$ERR_ARCH $ARCH"
    exit 1
fi
