#!/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 from 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 --title "`eval_gettext 'Select file to convert'`" --getopenfilename)
fi
[ -n "$in_files" ] || exit 0
while [ -z "$password" ]; do
    password=$($KDIALOG --title `basename "$in_files"` --password "`eval_gettext 'Enter password:'`")
    [ "$?" == "0" ] || exit 0
done
out_dir=$($KDIALOG --title "`eval_gettext 'Select output folder'`" --getexistingdirectory)
if [ -z "$out_dir" ] ; then
    out_dir=$($KDIALOG --title "`eval_gettext 'Select output folder'`" --getexistingdirectory)
fi
[ -n "$out_dir" ] || exit 0

out_text=`($OPENSSL enc $cipher_algo -d -a -pbkdf2 -pass pass:"$password" -in "$in_files" 2>&3 | tar -C "${out_dir}" -xf - 2>&3) 3>&1`

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