#!/usr/bin/env bash

export NCAD_VER=26.0
export NCAD_DASH_VER=${NCAD_VER/./-}

export XNANO=/opt/nanosoft/xnano${NCAD_VER}/bin/xnano64
export XNHOME="${HOME}"/.ncad_"${NCAD_VER}"x64

SPDS_APP_EXE="/opt/nanosoft/ncad_"${NCAD_VER}"/system_x64/drive_d/Nanosoft/nanoCAD x64 "${NCAD_VER}"/nCadS.exe"
SPDS_DEFAULT_ARGS="-b nSPDSComp -r SPDS -a nanoCAD_x64_SPDS_"${NCAD_VER}" -oleid {56443714-C478-4941-98DA-C5A0EAF0B124}"

/usr/bin/ncad-prep"${NCAD_DASH_VER}"

source /etc/default/ncad_cfg

if [ ! -z ${XN_USE_QT_FILEDLG+x} ]; then
    export XN_USE_QT_FILEDLG=1
fi

if [ `cat "${XNHOME}"/lic_agree` != "true" ]
then
	echo "Лицензия не принята. Для работы платформы примите, пожалуйста, лицензию";	exit 0
fi

#if first arg is a file - convert path (open dwg file with ncad default args)
if [ -f "$1" ]
then
        open_file_path=$(sed 's/\//\\/g' <<< "$1" | sed 's/^/Z\:/g')
	shift
else
	open_file_path=""
fi

#handling input args or use default args if opening dwg file
if [ "$#" -eq 0 ]
then
	echo -e "\033[43m\033[30m Args are not set. Using default args to run nanoCAD SPDS \033[0m"
	run_args="${SPDS_DEFAULT_ARGS}"
else
	run_str=""

        while [ -n "$1" ]
        do
                if [ -f "$1" ]
                then
                    run_str+="$(sed 's/\//\\/g' <<< "$1" | sed 's/^/Z\:/g')"
                else
                    run_str+="$1"
                fi
        #add space between params
                run_str+=" "
	shift
        done

	#delete space at the end of string
	run_args=$(sed 's/ $//g' <<< ${run_str})
fi
	"${XNANO}" start /unix "${SPDS_APP_EXE}" ${run_args} "${open_file_path}"
