#!/bin/sh


RUNFILE="${HOME}/bin/run_linux_app"
WINEPRFX="${HOME}/.wine"
NEED_EXT="bmp gif png jpg jpeg svg pdf tif tiff rtf doc docx xls xlsx odt ods vsd zip rar 7z eml"
output="REGEDIT4"$'\n'$'\n'

function install_handlers()
{
if [ ! -d "${WINEPRFX}" ]; then
    echo "Не существует такого WINE префикса ${WINEPRFX}"
    exit
fi

cp -f "${WINEPRFX}/system.reg" "${WINEPRFX}/system.reg.bak"
cp -f "${WINEPRFX}/user.reg" "${WINEPRFX}/user.reg.bak"
cp -f "${WINEPRFX}/userdef.reg" "${WINEPRFX}/userdef.reg.bak"

mkdir -p ${HOME}/bin/

cat > ${RUNFILE} <<-'_RUN_LINUX_APP_SCRIPT'
#!/bin/bash
xdg-open "$(winepath --unix "$1")"
_RUN_LINUX_APP_SCRIPT

chmod a+x ${RUNFILE}
winpath2script=$(winepath --windows "${HOME}/bin/run_linux_app")
command="${winpath2script//\\/\\\\} \\\"%1\\\""

for ext in ${NEED_EXT}; do
    #echo ${ext}
    output+="[HKEY_CLASSES_ROOT\\.${ext}]"$'\n'
    output+="@=\"UniversalHandlerW2L\""$'\n\n'
done

output+="[HKEY_CLASSES_ROOT\\UniversalHandlerW2L\\shell\\open\\command]"$'\n'
output+="@=\"${command}\""$'\n'
output+=$'\n'

printf '%s' "$output" > "${HOME}/bin/dump.reg"

env WINEPREFIX="${WINEPRFX}" wine regedit "${HOME}/bin/dump.reg"
rm -f "${HOME}/bin/dump.reg"
}

function install_shell_script()
{
PWD=`pwd`
START=start_qadmin.sh
rm -f ${START}
echo "#!/bin/sh" > ${START}
echo "" >> ${START}
echo "QAEXE=qadmin.exe" >> ${START}
echo "LOG=\${QAEXE}.log" >> ${START}
echo "export LANG=ru_RU.UTF-8" >> ${START}
echo "cd ${PWD}" >> ${START}
echo "date >> \${LOG}" >> ${START}
echo "wine ${PWD}/\${QAEXE} >> \${LOG} 2>&1" >> ${START}
chmod +x ${START}
}

function install_desktop_file()
{
RUN=qadmin.desktop
rm -f ${RUN}
echo "[Desktop Entry]" > ${RUN}
echo "Name=Quik Administrator" >> ${RUN}
echo "Name[ru]=Quik Administrator" >> ${RUN}
echo "Type=Application" >> ${RUN}
echo "NoDisplay=false" >> ${RUN}
echo "Hidden=false" >> ${RUN}
echo "Terminal=false" >> ${RUN}
echo "StartupNotify=false" >> ${RUN}
echo "Categories=Utility" >> ${RUN}

echo "Exec=${PWD}/${START}" >> ${RUN}
echo "Icon=${PWD}/qadmin.ico" >> ${RUN}
}

if [ ! -f "${RUNFILE}" ]; then
    install_handlers > /dev/null 2>&1
fi

install_shell_script
install_desktop_file
