#!/bin/sh

export TEXTDOMAIN="kde-file-actions-gost" TEXTDOMAINDIR="/usr/share/locale"
. gettext.sh
. shell-quote

KDIALOG=kdialog
OPENSSL="/usr/bin/openssl"
in_files="$@"
password=
ossl_version=`$OPENSSL version | sed -E -e 's|^OpenSSL[[:space:]]*||' -e 's|[[:space:]].*$||'`
cipher_algo="-unknown-cipher-algo"
if [ `rpmvercmp "3" "$ossl_version"` ] ; then
cipher_algo="-kuznyechik-ecb"
else
cipher_algo="-grasshopper-ecb"
fi

# check gost cipher
if ! $OPENSSL ciphers|tr ':' '\n'|grep -qe '^GOST2012-' ; then
    $KDIALOG --title "`eval_gettext 'Protective convertion to GOST'`" \
    --msgbox "`eval_gettext 'No GOST support found in OpenSSL.<br/>You should install <strong>openssl-gost-engine</strong> package<br/>then turn in on by <strong>control openssl-gost enabled</strong> command.'`"
    exit 0
fi

if [ -z "$in_files" ] ; then
    in_files=$($KDIALOG --msgbox "`eval_gettext 'Select file to convert'`")
    exit 0
fi
[ -n "$in_files" ] || exit 0
while [ -z "$password" ]; do
    password=$($KDIALOG --title "`eval_gettext 'Protective convertion to GOST'`"  --newpassword "`eval_gettext 'Create password:'`")
    [ "$?" == "0" ] || exit 0
done
encrypt=$($KDIALOG --title "`eval_gettext 'Select output file'`" --getsavefilename)
if [ -z "$encrypt" ] ; then
    encrypt=$($KDIALOG --title "`eval_gettext 'Select output file'`" --getsavefilename)
fi
[ -n "$encrypt" ] || exit 0

out_text=`(tar -c "$@" 2>&3 | $OPENSSL enc $cipher_algo -a -pbkdf2 -pass pass:"$password" -salt -out "$encrypt" 2>&3) 3>&1`

if [ "$?" == "0" ] ; then
    if ! $KDIALOG \
        --title "`eval_gettext 'Protective convertion to GOST'`" \
        --yesno "`eval_gettext 'Files converted succesfully.'`" \
        --yes-label "`eval_gettext 'OK'`" \
        --no-label "`eval_gettext 'Open folder'`"
    then
	xdg-open `dirname "$encrypt"`
    fi
else
    $KDIALOG --title "`eval_gettext 'Protective convertion to GOST'`" --detailederror "`eval_gettext 'Error'`" "$out_text"
fi
