#!/usr/bin/env bash

export fts=$(mktemp -u --tmpdir find-ts.XXXXXXXX)
export fpipe=$(mktemp -u --tmpdir find.XXXXXXXX)
mkfifo "$fpipe"


trap "exit_ubfind" EXIT

export find_cmd='@bash -c "run_find %1 %2 %3 %7 %8 %9 %10 %12 %13 %14 %15 %16 %18 %19 %20 %21"'
export open_cmd='@bash -c "open_file %s"'

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

init(){
    path_root=""
    export TEXTDOMAIN=$(basename ${0%.*})
    export TEXTDOMAINDIR="${path_root}/usr/share/locale"

    export catdoc_check="@disabled@"
    export docx2txt_check="@disabled@"
    export odt2txt_check="@disabled@"
    export pdfgrep_check="@disabled@"
    export python_xlsx2csv_check="@disabled@"
    export catdoc_tooltip="!$(i18n "Install %s to activate this item" "catdoc")"
    export docx2txt_tooltip="!$(i18n "Install %s to activate this item" "docx2txt")"
    export odt2txt_tooltip="!$(i18n "Install %s to activate this item" "odt2txt")"
    export pdfgrep_tooltip="!$(i18n "Install %s to activate this item" "pdfgrep")"
    export python_xlsx2csv_tooltip="!$(i18n "Install %s(AUR) to activate this item" "python_xlsx2csv")" #"

    if which catdoc &>/dev/null ; then
        catdoc_check="yes"
        catdoc_tooltip=""
    fi

    if which docx2txt &>/dev/null ; then
        docx2txt_check="yes"
        docx2txt_tooltip=""
    fi

    if which odt2txt &>/dev/null ; then
        odt2txt_check="yes"
        odt2txt_tooltip=""
    fi

    if which pdfgrep &>/dev/null ; then
        pdfgrep_check="yes"
        pdfgrep_tooltip=""
    fi

    if which python-xlsx2csv &>/dev/null ; then
        python_xlsx2csv_check="yes"
        python_xlsx2csv_tooltip=""
    fi

    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"
}


fkey=$(($RANDOM))

function exit_ubfind
{
    rm -f $fpipe $fts
    exec 3>&-
    exit 0
}
export -f exit_ubfind

function open_file
{
    xdg-open "${2}" # Открывть через дескриптор !
}
export -f open_file

function fn_pow_byte () { 

    prefix=$1
    size_pow=0
    if [ -z "${prefix}" ]; then
        size_pow=0
    elif [[ $prefix =~ .*b.* ]] || [[ $prefix  =~  .*б.* ]] || [[ $prefix =~ .*B.* ]] || [[ $prefix =~ .*Б.* ]]; then 
        size_pow=1
    elif [[ $prefix =~ .*k.* ]] || [[ $prefix =~ .*к.* ]] || [[ $prefix =~ .*K.* ]] || [[ $prefix =~ .*К.* ]]; then 
        size_pow=2
    elif [[ $prefix =~ .*m.* ]] || [[ $prefix =~ .*м.* ]] || [[ $prefix =~ .*M.* ]] || [[ $prefix =~ .*М.* ]]; then 
        size_pow=3
    elif [[ $prefix =~ .*g.* ]] || [[ $prefix =~ .*г.* ]] || [[ $prefix =~ .*G.* ]] || [[ $prefix =~ .*Г.* ]]; then 
        size_pow=4
    elif [[ $prefix =~ .*t.* ]] || [[ $prefix =~ .*т.* ]] || [[ $prefix =~ .*T.* ]] || [[ $prefix =~ .*Т.* ]]; then 
        size_pow=5
    else
        size_pow=0
    fi
    return $size_pow
}
export -f fn_pow_byte

function run_find
{
    local name="$1"
    local regex_chk="$2"
    local regist_chk="$3"
    local doc_chk="$4"
    local docx_chk="$5"
    local xls_chk="$6"
    local xlsx_chk="$7"
    local path="$8"
    local content="$9"

    local date="${10}"
    local size_more="${11}"
    local size_less="${12}"
    local odt_chk="${13}"
    local odf_chk="${14}"
    local pdf_chk="${15}"
    local txt_chk="${16}"

    local ARGS_DOC=""
    local ARGS_DOCX=""
    local ARGS_XLS=""
    local ARGS_XLSX=""
    local ARGS_ODT=""
    local ARGS_ODF=""
    local ARGS_PDF=""
    local ARGS_TXT=""
    
    declare -a DOC_ARR; declare -a DOC_ARR_TMP
    declare -a DOCX_ARR; declare -a DOCX_ARR_TMP
    declare -a ODT_ARR; declare -a ODT_ARR_TMP
    declare -a ODF_ARR; declare -a ODF_ARR_TMP
    declare -a XLS_ARR; declare -a XLS_ARR_TMP
    declare -a XLSX_ARR; declare -a XLSX_ARR_TMP
    declare -a PDF_ARR
    declare -a TXT_ARR
    ## content="$(echo "${content}" | sed 's/\*//g')"
    if  [[ -n "$name" ]]; then
    if [[ -n "$size_more" ]]; then
        fn_pow_byte "$size_more"
        pow_byte=$?
        
        size_more=$(echo "$size_more" | sed -e 's/[^0-9]//g')
            if [[ "${pow_byte}" -eq "0" ]]; then
                ""
            else
                byte1=$((1024**$pow_byte))
                size_more=$(($size_more * $byte1))
            
        fi
        

    fi


    if [[ -n "$size_less" ]]; then
        fn_pow_byte "$size_less"
        pow_byte=$?
        
        size_less=$(echo "$size_less" | sed -e 's/[^0-9]//g')
            if [[ "${pow_byte}" -eq "0" ]]; then
                ""
            else
                byte1=$((1024**$pow_byte))
                size_less=$(($size_less * $byte1))
            
        fi
        

    fi 
    
    if [ "$regex_chk" != "TRUE" ] && [ -n "$content" ]; then
        content="-i $(echo "${content}" | sed 's/\*//g')"
    else
        content="$(echo "${content}" | sed 's/\*//g')"
    fi 

    if [ -z "$name" ]; then
        name="*"
    fi
    [[ "$regist_chk" == "TRUE" ]] && unset regist_chk || regist_chk="i"
    if [ "$regex_chk" != "TRUE" ]; then
        [[ "$doc_chk" == "TRUE" ]] && ARGS_DOC+=" -${regist_chk}name '$name.doc'"
        [[ "$docx_chk" == "TRUE" ]] && ARGS_DOCX+=" -${regist_chk}name '$name.docx'"
        [[ "$xls_chk" == "TRUE" ]] && ARGS_XLS+=" -${regist_chk}name '$name.xls'"
        [[ "$xlsx_chk" == "TRUE" ]] && ARGS_XLSX+=" -${regist_chk}name '$name.xlsx'"
        [[ "$odt_chk" == "TRUE" ]] && ARGS_ODT+=" -${regist_chk}name '$name.odt'"
        [[ "$odf_chk" == "TRUE" ]] && ARGS_ODF+=" -${regist_chk}name '$name.odf'"
        [[ "$pdf_chk" == "TRUE" ]] && ARGS_PDF+=" -${regist_chk}name '$name.pdf'"
        [[ "$txt_chk" == "TRUE" ]] && ARGS_TXT+=" -${regist_chk}name '$name.txt'"
    else
        [[ "$doc_chk" == "TRUE" ]] && ARGS_DOC+=" -${regist_chk}regex '$name.doc'"
        [[ "$docx_chk" == "TRUE" ]] && ARGS_DOCX+=" -${regist_chk}regex '$name.docx'"
        [[ "$xls_chk" == "TRUE" ]] && ARGS_XLS+=" -${regist_chk}regex '$name.xls'"
        [[ "$xlsx_chk" == "TRUE" ]] && ARGS_XLSX+=" -${regist_chk}regex '$name.xlsx'"
        [[ "$odt_chk" == "TRUE" ]] && ARGS_ODT+=" -${regist_chk}regex '$name.odt'"
        [[ "$odf_chk" == "TRUE" ]] && ARGS_ODF+=" -${regist_chk}regex '$name.odf'"
        [[ "$pdf_chk" == "TRUE" ]] && ARGS_PDF+=" -${regist_chk}regex '$name.pdf'"
        [[ "$txt_chk" == "TRUE" ]] && ARGS_TXT+=" -${regist_chk}regex '$name.txt'"
    fi

    if [ -n "${size_more}" ] && [ "${size_more}" -gt "0" ]; then
        [[ "$doc_chk" == "TRUE" ]] && ARGS_DOC+=" -size +${size_more}c"
        [[ "$docx_chk" == "TRUE" ]] && ARGS_DOCX+=" -size +${size_more}c"
        [[ "$xls_chk" == "TRUE" ]] && ARGS_XLS+=" -size +${size_more}c"
        [[ "$xlsx_chk" == "TRUE" ]] && ARGS_XLSX+=" -size +${size_more}c"
        [[ "$odt_chk" == "TRUE" ]] && ARGS_ODT+=" -size +${size_more}c"
        [[ "$odf_chk" == "TRUE" ]] && ARGS_ODF+=" -size +${size_more}c"
        [[ "$pdf_chk" == "TRUE" ]] && ARGS_PDF+=" -size +${size_more}c"
        [[ "$txt_chk" == "TRUE" ]] && ARGS_TXT+=" -size +${size_more}c"
    fi

    if [ -n "${size_less}" ] && [ "${size_less}" -gt "0" ]; then
        [[ "$doc_chk" == "TRUE" ]] && ARGS_DOC+=" -size -${size_less}c"
        [[ "$docx_chk" == "TRUE" ]] && ARGS_DOCX+=" -size -${size_less}c"
        [[ "$xls_chk" == "TRUE" ]] && ARGS_XLS+=" -size -${size_less}c"
        [[ "$xlsx_chk" == "TRUE" ]] && ARGS_XLSX+=" -size -${size_less}c"
        [[ "$odt_chk" == "TRUE" ]] && ARGS_ODT+=" -size -${size_less}c"
        [[ "$odf_chk" == "TRUE" ]] && ARGS_ODF+=" -size -${size_less}c"
        [[ "$pdf_chk" == "TRUE" ]] && ARGS_PDF+=" -size -${size_less}c"
        [[ "$txt_chk" == "TRUE" ]] && ARGS_TXT+=" -size -${size_less}c"
    fi

    if [ -n "$date" ]; then
        dt=$(echo "$date" | awk -F. '{printf "%s-%s-%s", $3, $2, $1}')
        touch -d "$dt" "$fts"
        [[ "$doc_chk" == "TRUE" ]] && ARGS_DOC+=" -newer $fts"
        [[ "$docx_chk" == "TRUE" ]] && ARGS_DOCX+=" -newer $fts"
        [[ "$xls_chk" == "TRUE" ]] && ARGS_XLS+=" -newer $fts"
        [[ "$xlsx_chk" == "TRUE" ]] && ARGS_XLSX+=" -newer $fts"
        [[ "$odt_chk" == "TRUE" ]] && ARGS_ODT+=" -newer $fts"
        [[ "$odf_chk" == "TRUE" ]] && ARGS_ODF+=" -newer $fts"
        [[ "$pdf_chk" == "TRUE" ]] && ARGS_PDF+=" -newer $fts"
        [[ "$txt_chk" == "TRUE" ]] && ARGS_TXT+=" -newer $fts"
    fi

    if [ "$content" == "." ]; then
        content=""
    fi

    
    if [ -n "$content" ]; then
        ARGS_PDF+=" -exec pdfgrep -H "$content" {} + | sed 's/:.*//'"
        ARGS_TXT+=" -exec grep -H "$content" {} + | sed 's/:.*//'"
    fi

    echo -e "\f" >> "$fpipe"
    

########## FIND .DOC ##########



    if [ "$doc_chk" == "TRUE" ]; then
        while read -r doc_line; do
            [[ -n "$content" ]] && DOC_ARR_TMP+=("$doc_line") || \
                DOC_ARR+=("$doc_line")
        done < <(eval find "'$path'" $ARGS_DOC)

        if [ -n "$content" ]; then 
            for path_doc_tmp in "${DOC_ARR_TMP[@]}"; do
                DOC_ARR+=("$(catdoc "$path_doc_tmp" | grep -H --label="$path_doc_tmp" -n "$content" | sed 's/:.*//')")
            done
        fi

        while IFS= read -r path_doc; do
            if [ -n "${path_doc}" ]; then
                echo "$(stat -c "%n|%s|%A|%.19y|%G/%U" "${path_doc}")" | sed 's/|/\n/g' >> "$fpipe"
            fi
        done < <(printf "%s\n" "${DOC_ARR[@]}" | sort -u)
    fi
########## FIND .DOC ##########

########## FIND .DOCX ##########
    if [ "$docx_chk" == "TRUE" ]; then
        while read -r docx_line; do
            [[ -n "$content" ]] && DOCX_ARR_TMP+=("$docx_line") || \
                DOCX_ARR+=("$docx_line")
        done < <(eval find "'$path'" -type f "$ARGS_DOCX")

        if [ -n "$content" ]; then 
            for path_docx_tmp in "${DOCX_ARR_TMP[@]}"; do
                DOCX_ARR+=("$(docx2txt < "$path_docx_tmp" | grep -H --label="$path_docx_tmp" -n "$content" | sed 's/:.*//')")
            done
        fi

        while IFS= read -r path_docx; do 
            if [ -n "${path_docx}" ]; then
                echo "$(stat -c "%n|%s|%A|%.19y|%G/%U" "${path_docx}")" | sed 's/|/\n/g' >> "$fpipe"
            fi
        done < <(printf "%s\n" "${DOCX_ARR[@]}" | sort -u)
    fi
########## FIND .DOCX ##########

########## FIND .XLS ##########
    if [ "$xls_chk" == "TRUE" ]; then
        while read -r xls_line; do
            [[ -n "$content" ]] && XLS_ARR_TMP+=("$xls_line") || \
                XLS_ARR+=("$xls_line")
        done < <(eval find "'$path'" -type f "$ARGS_XLS")

        if [ -n "$content" ]; then 
            for path_xls_tmp in "${XLS_ARR_TMP[@]}"; do
                XLS_ARR+=("$(xls2csv "$path_xls_tmp" | grep -H --label="$path_xls_tmp" -n "$content" | sed 's/:.*//')")
            done
        fi

        while IFS= read -r path_xls; do 
            if [ -n "${path_xls}" ]; then
                echo "$(stat -c "%n|%s|%A|%.19y|%G/%U" "${path_xls}")" | sed 's/|/\n/g' >> "$fpipe"
            fi
        done < <(printf "%s\n" "${XLS_ARR[@]}" | sort -u)
    fi
########## FIND .XLS ##########

########## FIND .XLSX ##########
    if [ "$xlsx_chk" == "TRUE" ]; then
        while read -r xlsx_line; do
            [[ -n "$content" ]] && XLSX_ARR_TMP+=("$xlsx_line") || \
                XLSX_ARR+=("$xlsx_line")
        done < <(eval find "'$path'" -type f "$ARGS_XLSX")

        if [ -n "$content" ]; then 
            for path_xlsx_tmp in "${XLSX_ARR_TMP[@]}"; do
                XLSX_ARR+=("$(xlsx2csv "$path_xlsx_tmp" | grep -H --label="$path_xlsx_tmp" -n "$content" | sed 's/:.*//')")
            done
        fi

        while IFS= read -r path_xlsx; do 
            if [ -n "${path_xlsx}" ]; then
                echo "$(stat -c "%n|%s|%A|%.19y|%G/%U" "${path_xlsx}")" | sed 's/|/\n/g' >> "$fpipe"
            fi
        done < <(printf "%s\n" "${XLSX_ARR[@]}" | sort -u)
    fi
########## FIND .XLSX ##########

########## FIND .ODT ##########
    if [ "$odt_chk" == "TRUE" ]; then
        while read -r odt_line; do
            [[ -n "$content" ]] && ODT_ARR_TMP+=("$odt_line") || \
                ODT_ARR+=("$odt_line")
        done < <(eval find "'$path'" -type f "$ARGS_ODT")

        if [ -n "$content" ]; then 
            for path_odt_tmp in "${ODT_ARR_TMP[@]}"; do
                ODT_ARR+=("$(odt2txt "$path_odt_tmp" | grep -H --label="$path_odt_tmp" -n "$content" | sed 's/:.*//')")
            done
        fi

        while IFS= read -r path_odt; do 
            if [ -n "${path_odt}" ]; then
                echo "$(stat -c "%n|%s|%A|%.19y|%G/%U" "${path_odt}")" | sed 's/|/\n/g' >> "$fpipe"
            fi
        done < <(printf "%s\n" "${ODT_ARR[@]}" | sort -u)
    fi
########## FIND .ODT ##########

########## FIND .ODF ##########
    if [ "$odf_chk" == "TRUE" ]; then
        while read -r odf_line; do
            [[ -n "$content" ]] && ODF_ARR_TMP+=("$odf_line") || \
                ODF_ARR+=("$odf_line")
        done < <(eval find "'$path'" -type f "$ARGS_ODF")

        if [ -n "$content" ]; then 
            for path_odf_tmp in "${ODF_ARR_TMP[@]}"; do
                ODF_ARR+=("$(odt2txt "$path_odf_tmp" | grep -H --label="$path_odf_tmp" -n "$content" | sed 's/:.*//')")
            done
        fi

        while IFS= read -r path_odf; do 
            if [ -n "${path_odf}" ]; then
                echo "$(stat -c "%n|%s|%A|%.19y|%G/%U" "${path_odf}")" | sed 's/|/\n/g' >> "$fpipe"
            fi
        done < <(printf "%s\n" "${ODF_ARR[@]}" | sort -u)
    fi
########## FIND .ODF ##########

########## FIND .PDF ##########
    if [ "$pdf_chk" == "TRUE" ]; then
        while read -r pdf_line; do
                PDF_ARR+=("$pdf_line")
        done < <(eval find "'$path'" -type f "$ARGS_PDF")

        while IFS= read -r path_pdf; do 
            if [ -n "${path_pdf}" ]; then
                echo "$(stat -c "%n|%s|%A|%.19y|%G/%U" "${path_pdf}")" | sed 's/|/\n/g' >> "$fpipe"
            fi
        done < <(printf "%s\n" "${PDF_ARR[@]}" | sort -u)
    fi
########## FIND .PDF ##########

########## FIND .TXT ##########
    if [ "$txt_chk" == "TRUE" ]; then
        while read -r txt_line; do
                TXT_ARR+=("$txt_line")
        done < <(eval find "'$path'" -type f "$ARGS_TXT")

        while IFS= read -r path_txt; do 
            if [ -n "${path_txt}" ]; then
                [[ -n "${path_txt}" ]] && echo "$(stat -c "%n|%s|%A|%.19y|%G/%U" "${path_txt}")" | sed 's/|/\n/g' >> "$fpipe"
            fi
        done < <(printf "%s\n" "${TXT_ARR[@]}" | sort -u)
    fi
########## FIND .TXT ##########
    fi
}
export -f run_find

init

exec 3<> $fpipe

yad --plug="$fkey" \
    --tabnum=1 \
    --form \
    --columns=2 \
    --field=$"$(i18n "Name")" '' \
    --field=$"$(i18n "Use regex"):chk" 'no' \
    --field=$"$(i18n "Case sensitivity"):chk" 'no' \
    --field=$" :lbl" '' \
    --field=$" :lbl" '' \
    --field=$"$(i18n "Format"):lbl" '' \
    --field=$".doc${catdoc_tooltip}:chk" "$catdoc_check" \
    --field=$".docx${docx2txt_tooltip}:chk" "$docx2txt_check" \
    --field=$".xls${catdoc_tooltip}:chk" "$catdoc_check" \
    --field=$".xlsx${python_xlsx2csv_tooltip}:chk" "$python_xlsx2csv_check" \
    --field=$" :lbl" '' \
    --field=$"$(i18n "Directory"):dir" "$HOME" \
    --field=$"$(i18n "Content")" '' \
    --field=$"$(i18n "Newer then"):dt" '' \
    --field=$"$(i18n "More than (in byte)")" '' \
    --field=$"$(i18n "Less then (in byte)")" '' \
    --field=$" :lbl" '' \
    --field=$".odt${odt2txt_tooltip}:chk" "$odt2txt_check" \
    --field=$".odf${odt2txt_tooltip}:chk" "$odt2txt_check" \
    --field=$".pdf${pdfgrep_tooltip}:chk" "$pdfgrep_check" \
    --field=$".txt:chk" 'yes' \
    --field="yad-search:fbtn" "$find_cmd" &

yad --plug="$fkey" \
    --tabnum=2 \
    --list \
    --no-markup \
    --dclick-action="${open_cmd}" \
    --text $"$(i18n "Search results"):" \
    --column=$"$(i18n "Name")" \
    --column=$"$(i18n "Size"):sz" \
    --column=$"$(i18n "Perms")" \
    --column=$"$(i18n "Date")" \
    --column=$"$(i18n "Owner")" \
    --search-column=1 \
    --expand-column=0  <&3 &


yad --paned \
    --key="$fkey" \
    --button="yad-close:1" \
    --width=930 \
    --height=670 \
    --title=$"$(i18n "Find files")" \
    --window-icon="ubfind"

exec 3>&-

exit 0
