#!/usr/bin/env bash

VERSION=1.1

USERNAME="alo"
PASSWORD="2dda2a9320a936944ac6b7f99fab509d"
WEB_REPORT="https://report.ublinux.ru/${USERNAME}/"

i18n() {
    local key="$1"; shift
    printf "$(gettext -s "$key")" "$@"
}   
export -f i18n

type_file() { type "$1" &>/dev/null;}

init(){
    export TEXTDOMAIN="$(basename "${0%.*}")"
    export TEXTDOMAINDIR="${path_root}/usr/share/locale"
    export pipe=$(mktemp -u --tmpdir ubhwreport.XXXX)
    export isAuto="False"

    LC_ALL="ru_RU.UTF-8"
    LANG="ru_RU.UTF-8"
    LANGUAGE="en_US:en:ru_RU:ru"
    LC_PAPER="en_US.UTF-8"
    LESSCHARSET="utf-8"
    MM_CHARSET="utf-8"
    
    while :; do
    type_file dialog && DIA="dialog --aspect 20 " && DIA_ESC=-- && break
    type_file gdialog && DIA=gdialog && break
    exec date +%F $(i18n "No Dialog program found!")
    done
}
export -f init
init

msg_version="UBHWReport, version %s
Copyright (C) 2022 Ubiteh, Inc.
License GPLv3+: GNU GPL version 3 or later <http://ublinux.ru>"

msg_help="UBHWReport console application for generate reports and sending it to Ubiteh

    Usage:    %s [-h -a]

    -h
        Show a help message
    -a
        Automatic report sending
"

generate_report(){
    local message="$1"
    local messageTitle="$(i18n "Message for technical support service:")"
    local reportText="$(hardinfo -rsaf text 2>/dev/null | sed '/^Тесты$/,$d')"

    [ -n "$message" ] && reportText=$(cat <<< $reportText | sed "4 a $messageTitle" | sed "5 a $message")
    echo "$reportText"
}
export -f generate_report

send_report(){
    # TODO: написать отправку отчета
    sleep 1
    local PATH_REPORT=$(mktemp -d --tmpdir ubhwreport.XXXX)
    local FILE_REPORT="ubhwreport-$(lspci -nmm | md5sum | cut -f1 -d" ")-$(date '+%Y%m%d-%H:%M').gz"
    echo $1 | gzip > ${PATH_REPORT}/${FILE_REPORT}
    curl -u ${USERNAME}:${PASSWORD} -T ${PATH_REPORT}/${FILE_REPORT} ${WEB_REPORT}
    local STATUS=$?
    rm -rdf ${PATH_REPORT}
    [[ STATUS -eq 0 ]] && return 0 || return 1
}
export -f send_report

main_dialog(){
    local utilDesc="$(i18n "The program generates a hardware report and sends this report to the developer's support service.")"
    local input
    local reportText

    # Главное окно
    if [ "$isAuto" != "True" ]; then
        if [ -n "$XDG_CURRENT_DESKTOP" ]; then
            input="$(yad --center \
                --title="$(i18n "Send report")" \
                --text="$utilDesc" \
                --image=ublinux-ubhwreport_1 \
                --window-icon=ublinux-ubhwreport \
                --form \
                --field="$(i18n "Message to technical support service:"):txt" \
                --button="$(i18n "Create report"):0" \
                --borders=18 \
                --width=480 \
                --height=320)"
            [ "$?" != "0" ] && exit 1
            input="$(echo $input | tr -d '|')"
        else
            echo -e "$utilDesc\n"
            read -p "Message to developers: " input
        fi
    fi

    # Генерация отчета
    if [ -n "$XDG_CURRENT_DESKTOP" ]; then
        generate_report "$input" | tee >(cat > $pipe) | yad --progress \
            --title="$(i18n "Report generation...")" \
            --window-icon=ublinux-ubhwreport \
            --width=300 \
            --borders=16 \
            --pulsate \
            --auto-close \
            --no-buttons \
            --auto-kill \
            --skip-taskbar
        reportText=$(cat $pipe)
    else
        echo "$(i18n "Report generation...")"
        reportText=$(generate_report "$input")
    fi

    # Окно отправки отчета
    if [ "$isAuto" != "True" ]; then
        if [ -n "$XDG_CURRENT_DESKTOP" ]; then
            yad --center \
                --text="$(i18n "Generated report for developer's support service")" \
                --image=ublinux-ubhwreport_2 \
                --window-icon=ublinux-ubhwreport \
                --title="$(i18n "Send report")" \
                --button="$(i18n "Send report"):0" \
                --text-info <<< $reportText \
                --borders=16 \
                --geometry=640x480
            [ "$?" != "0" ] && exit 1
        else
            while [ "$selection" != "y" ]; do
                echo -e "Are you want to send the report?"
                read -p "[y/n]: " selection
                [ "$selection" == "n" ] && exit 1
            done
        fi
    fi

    # Отправка отчета
    if [ -n "$XDG_CURRENT_DESKTOP" ]; then
        send_report "$reportText" | yad --progress \
            --title="$(i18n "Report sending...")" \
            --window-icon=ublinux-ubhwreport \
            --width=300 \
            --borders=16 \
            --pulsate \
            --auto-close \
            --no-buttons \
            --auto-kill \
            --skip-taskbar
        rCode="$?"
    else
        echo "$(i18n "Report sending...")"
        send_report "$reportText"
        rCode="$?"
    fi

    # Результат отправки
    if [ -n "$XDG_CURRENT_DESKTOP" ]; then
        if [ "$rCode" == "0" ]; then
            yad --center \
                --title="$(i18n "Warning")" \
                --width="405" \
                --fixed \
                --skip-taskbar \
                --button="yad-close:0" \
                --buttons-layout=center \
                --borders=12 \
                --image="emblem-default" \
                --window-icon=ublinux-ubhwreport \
                --text="$(i18n "The report has been sent to the developer's technical support service.")" \
                --text-width="24"
            return 0
        else
            yad --center \
                --title="$(i18n "Warning")" \
                --width="405" \
                --fixed \
                --skip-taskbar \
                --button="yad-close:0" \
                --buttons-layout=center \
                --borders=12 \
                --image="emblem-danger" \
                --window-icon=ublinux-ubhwreport \
                --text="$(i18n "An error occurred while sending a report to the developer's technical support service.")" \
                --text-width="24"
            return 1
        fi
    else
        if [ "$rCode" == "0" ]; then
            echo "$(i18n "The report has been sent to the developer's technical support service.")"
            return 0
        else
            echo "$(i18n "An error occurred while sending a report to the developer's technical support service.")"
            return 1
        fi
    fi
}
export -f main_dialog

if [ "$1" == "-h" ]; then
    echo -e "$(i18n "${msg_version}" "${VERSION}")"
    echo -e "$(i18n "${msg_help}" "$(basename $0)") \n"
    exit 0
else
    [ "$1" == "-a" ] && isAuto="True"
    main_dialog && exit 0 || exit 1
fi

exit 1