#!/usr/bin/env bash

VERSION=1.2

USERNAME="ublinux"
PASSWORD="0bc02e0fc443c523de246632382ee6d5"
URL_REPORT="https://robot.ublinux.ru"
PATH_ROOT=

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

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

init(){
    export TEXTDOMAIN="${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"
    BIN_RUSTDESK="/usr/bin/rustdesk"
    
    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 support

    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')"
    local reportText="$(hardinfo -rsaf text 2>/dev/null)"

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

send_report(){
    local PATH_REPORT="$(mktemp -d --tmpdir ubhwreport.XXXX)" && trap "rm -f ${PATH_REPORT}" 0 2 3 15
    local FILE_REPORT="ubhwreport-$(lspci -nmm | md5sum | cut -f1 -d" ")-$(date '+%Y%m%d-%H:%M').xz"
    local reportText="$1"

    sleep 1
    reportText="${reportText}\n
$(i18n "Remote support service:")
---------------------------\n
$(grep 'id\|password' ~/.config/rustdesk/RustDesk.toml)"
    echo -e "${reportText}" | xz -9 > "${PATH_REPORT}/${FILE_REPORT}"
    REPLY_CURL="$(curl --silent --user ${USERNAME}:${PASSWORD} -F "upload=@${PATH_REPORT}/${FILE_REPORT}" "${URL_REPORT}/?mode=hwreport&os-codename=$(cat /etc/os-release | grep "VERSION_CODENAME" | cut -d'=' -f2)")" #"
    echo "${REPLY_CURL}" >&2 
    rm -rdf ${PATH_REPORT}
    head -1 <<< ${REPLY_CURL} | grep -q "STATUS: Content size correct" && STATUS=0 || echo STATUS=1
    echo ${STATUS}
    return ${STATUS}
}
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
        generate_report "$input" | tee >(cat > $pipe) | zenity \
            --progress \
	    --pulsate \
	    --title="$(i18n "Report generation...")" \
            --text="$(i18n "Report generation...")" \
            --window-icon=/usr/share/icons/hicolor/16x16/apps/ublinux-ubhwreport.svg \
	    --width=250 \
	    --no-cancel \
	    --auto-close \
	    --auto-kill
        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
        [[ -f ${BIN_RUSTDESK} ]] && systemctl --user start ublinux-support.service
#        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
    	send_report "$reportText" | tee >(cat > $pipe) | zenity \
    	    --progress \
    	    --pulsate \
    	    --title="$(i18n "Report sending...")" \
    	    --text="$(i18n "Report sending...")" \
    	    --window-icon=/usr/share/icons/hicolor/16x16/apps/ublinux-ubhwreport.svg \
    	    --width=250 \
    	    --no-cancel \
    	    --auto-close \
    	    --auto-kill
    	rCode="$(cat $pipe)"
    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"
#                --image="emblem-default" \
#                --image="dialog-information" \
        else
            yad --center \
                --title="$(i18n "Warning!")" \
                --width="405" \
                --fixed \
                --skip-taskbar \
                --button="yad-close:0" \
                --buttons-layout=center \
                --borders=12 \
                --image="emblem-important" \
                --window-icon=ublinux-ubhwreport \
                --text="$(i18n "An error occurred while sending a report to the developer's technical support service.")" \
                --text-width="24"
#                --image="dialog-error" \
        fi
    else
        if [ "$rCode" == "0" ]; then
            echo "$(i18n "The report has been sent to the developer's technical support service.")"
        else
            echo "$(i18n "An error occurred while sending a report to the developer's technical support service.")"
        fi
    fi
    
    if [ "$isAuto" != "True" ]; then
        if [ -n "$XDG_CURRENT_DESKTOP" ]; then
    	    systemctl --user --quiet is-active ublinux-support.service && systemctl --user stop ublinux-support.service
    	fi
    fi
    [[ $rCode == "0" ]] && return 0 || return 1
}
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