#!/bin/bash
##INSTALA O SIG FRENTE ATUALIZADO
##By: RAFAEL RIBEIRO
##Revision: RAFAEL BORGES E CAIO SANTOS
##Atualizado: CRISTIANO RODRIGUES SIQUEIRA SOARES
##Revisão:

user=`whoami`
versao=$(lsb_release -r -s)
versaopdv=2408.1
vnfce=4.51.16
sigutilsni=0
instpasta='/tmp/install_sigfrente/'
if [[ $user == "root" ]]; then

	# Versão atualizada dos pacotes
	mkdir $instpasta
	chmod 777 $instpasta
	cd $instpasta
	apt update -y


	if [[ $versao == '16.04' ]];then
		sigutils='sigutils-2.4.9.tar.gz'
	elif [[ $versao == '18.04' ]];then
		sigutils='SigUtils-2.4.14.tar.gz'
	elif [[ $versao == '14.04' ]];then
		clear
		echo "╔═════════════════════╗"
		echo "║ Versão 14 do Linux  ║"
		echo "║ Caixa desatualizado ║"
		echo "║ Processo encerrado  ║"
		echo "╚═════════════════════╝"
		exit
	fi
	dltxt='download.sigsolucoes.net.br/produtos/crss/txt'
	dlpadrao='download.sigsolucoes.net.br/produtos/crss/PDV'
	sigfrente='sigpdvnfce-3.1.21L3.deb'
	pythonnfe='nfe-4.51.16.tar.gz'
	geraldo='geraldo_0.4.10-stable-sig.tar.gz'
	kiwi='python-kiwi_1.9.27-nmu1_all.deb'
	stoqdrivers='stoqdrivers_0.9.11.9i18_all.deb'
	pyxmlsec='pyxmlsec_0.3.1.orig.tar.gz'
	pyxmlsecdeb='python-pyxmlsec_0.3.1-1openhouse2_amd64.deb'
	xmlsec='xmlsec-0.3.1.tar.gz'
	pysqlalchemy='python-sqlalchemy_0.8.4-nmu1build1_all.deb'
	pysqlalchemydoc='python-sqlalchemy-doc_0.8.4-nmu1build1_all.deb'
	pyordereddict='python-ordereddict_1.1-2chl1~trusty1_all.deb'
	pyserial='python-serial_2.6-nmu1build1_all.deb'
	errorhandler='python-errorhandler_1.1.1-1_all.deb'
	xlutils='python-xlutils_1.5.1-1_all.deb'
	elixir='python-elixir_0.7.1-2_all.deb'
	vpostgresql='13'

	wget -c --progress=bar:force $dlpadrao/sig.jpg
	wget -c --progress=bar:force $dlpadrao/menu-sig.png
	wget -c --progress=bar:force $dltxt/start-sigpdv

	# Baixando pacotes
	wget -c --progress=bar:force $dlpadrao/$sigfrente
	wget -c --progress=bar:force $dlpadrao/$sigutils
	wget -c --progress=bar:force $dlpadrao/$pythonnfe
	wget -c --progress=bar:force $dlpadrao/$geraldo
	wget -c --progress=bar:force $dlpadrao/$kiwi
	wget -c --progress=bar:force $dlpadrao/$stoqdrivers
	wget -c --progress=bar:force $dlpadrao/$pyxmlsecdeb
	wget -c --progress=bar:force $dlpadrao/$errorhandler
	wget -c --progress=bar:force $dlpadrao/$xlutils
	wget -c --progress=bar:force $dlpadrao/$elixir
	wget -c --progress=bar:force $dlpadrao/$pyserial
	wget -c --progress=bar:force $dlpadrao/$pysqlalchemy
	wget -c --progress=bar:force $dlpadrao/$pysqlalchemydoc
	wget -c --progress=bar:force $dlpadrao/$pyordereddict
	chmod -R 777 $instpasta

	if  [ -e $sigfrente       ] && [ -e $kiwi          ] &&
		[ -e $sigutils        ] && [ -e $pythonnfe     ] &&
		[ -e $geraldo         ] && [ -e $stoqdrivers   ] &&
		[ -e $pyxmlsecdeb     ] && [ -e $errorhandler  ] &&
		[ -e $xlutils         ] && [ -e $elixir        ] &&
		[ -e $pyserial        ] && [ -e $pysqlalchemy  ] && 
		[ -e $pysqlalchemydoc ] && [ -e $pyordereddict ];then
		echo "╔════════════════════════════════╗"
		echo "║ Download efetuado com sucesso! ║"
		echo "╚════════════════════════════════╝"
	else
		echo "╔════════════════════════════════════════╗"
		echo "║ Não foi possível efetuar o download... ║"
		echo "╚════════════════════════════════════════╝"
		echo "╔════════════════════════════════════════════════════╗"
		echo "║ Verifique se os links de downloads estão corretos. ║"
		echo "╚════════════════════════════════════════════════════╝"
		exit
	fi

	# Instalando Pacotes Necessários
	echo "╔═════════════════════════════╗"
	echo "║ Obtendo pacotes Necessários ║"
	echo "╚═════════════════════════════╝"
	apt update -y
	apt -f install vim -y
	apt -f install openssh-server -y
	apt -f install ssh -y
	apt -f install terminator -y

	# Instalando dependencias dos pacotes SigPDV3.1-NFC-e
	echo -e "╔════════════════════════════════════════════════════╗"
	echo -e "║ Obtendo pacotes para instalação SigPDV3.1-NFC-e... ║"
	echo -e "╚════════════════════════════════════════════════════╝"
	apt update -y
	dpkg --add-architecture i386
	apt -f install python-pip -y
	apt -f install xmlsec1 -y
	apt -f install python-libxml2 -y
	apt -f install python-libxmlsec -y
	apt -f install python-openssl -y
	apt -f install python-lxml -y
	apt -f install libxmlsec1-openssl -y
	apt -f install libxmlsec1-dev -y
	apt -f install libxslt1-dev -y
	apt -f install zlib1g-dev -y
	apt -f install libxml2-dev -y
	apt -f install libxml2:amd64 -y
	apt -f install libxml2:i386 -y
	apt -f install lib32stdc++6 -y
	apt -f install libusb-0.1-4 -y
	apt -f install libtool -y
	apt -f install libqtgui4 -y
	apt -f install libqtcore4 -y
	apt -f install libqt4-xml -y
	apt -f install libqt4-test -y
	apt -f install libqt4-script -y
	apt -f install libqt4-network -y
	apt -f install libqt4-dbus -y
	apt -f install libgle3 -y
	apt -f install libssl-dev -y
	apt -f install libffi-dev -y
	apt -f install python3-smbc -y
	apt -f install python-opengl -y
	apt -f install python-setuptools -y
	apt -f install pyside-tools -y
	apt -f install python-requests -y
	apt -f install python-docutils -y
	apt -f install python2.7-zope -y
	apt -f install python-reportlab -y
	apt -f install python-psycopg2 -y
	apt -f install python-dateutil -y
	apt -f install python-keybinder -y
	apt -f install python-pil -y
	apt -f install python-pyside -y
	apt -f install python-pyside.qtopengl -y
	apt -f install python-dev -y
	apt -f install swig -y
	apt -f install default-libmysqlclient-dev -y
	apt -f install libmysqlclient-dev -y
	apt -f install python-usb -y
	apt -f install python-rex -y
	apt -f install python-qrcode -y
	apt -f install python-dnspython -y
	apt -f install python-crypto -y
	apt -f install python-m2crypto -y
	apt -f install python-mysqldb -y
	apt -f install python-beautifulsoup -y
	apt -f install python-qt4 -y
	apt -f install python-qt4-gl -y
	apt -f install qt4-designer -y
	apt -f install qt4-dev-tools -y
	apt -f install build-essential -y
	apt -f install autoconf -y
	apt -f install pkg-config -y
	apt -f install idle-python2.7 -y

	# Instalação Postgresql

	#apt install postgresql -y
	if [[ $versao < "20.04" ]];then
		sudo sh -c 'echo "deb https://apt-archive.postgresql.org/pub/repos/apt bionic-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
	elif [[ $versao -le "20.04" ]];then
		sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
	fi
	wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
	apt update -y
	apt install postgresql-13 postgresql-client-13 -y

	if [[ -e /etc/postgresql/15/main/ ]];then
		apt --purge remove postgresql-15 -y
	fi

	# Configurações Postgres

	echo -e "╔════════════════════════════════════════════════════════════════╗"
	echo -e "║ Configuração do postgres alterado para utilização do SigFrente ║"
	echo -e "╚════════════════════════════════════════════════════════════════╝"
	cd /etc/postgresql/$vpostgresql/main/
	sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/g" postgresql.conf
	sed -i "s/127.0.0.1\/32/0.0.0.0\/0/g" pg_hba.conf
	sed -i "s/md5/trust/g" pg_hba.conf
	sed -i "s/peer/trust/g" pg_hba.conf
	/etc/init.d/postgresql reload
	/etc/init.d/postgresql restart
	createdb -U postgres -E utf8 sigpdv -h localhost
#    psql -c "ALTER USER postgres WITH PASSWORD ''" -d template1


	apt -f install pgadmin3 -y
	apt -f install --reinstall cups-filters -y
	pip install segno
	pip install pytz
	pip install "cython<0.23"

	# Instalado Pacote Python-Kiwi

	echo -e "╔═══════════════════════════════╗"
	echo -e "║ Instalando pacote Python-Kiwi ║"
	echo -e "╚═══════════════════════════════╝"
	cd $instpasta
	dpkg -i $kiwi
	sleep 3

	# Instalando Pacote Geraldo-Stable

	echo -e "╔══════════════════════════════════╗"
	echo -e "║ Instalando pacote Geraldo-Stable ║"
	echo -e "╚══════════════════════════════════╝"
	cd $instpasta
	tar xfvz $geraldo
	cd $instpasta/Geraldo-0.4.10-stable-sig/
	python setup.py install
	sleep 3

	# Instalado Pacote PyXmlSec.deb

	echo -e "╔════════════════════════════════╗"
	echo -e "║ Instalando pacote PyXmlSec.deb ║"
	echo -e "╚════════════════════════════════╝"
	cd $instpasta
	dpkg -i $pyxmlsecdeb
	sleep 3
	
	# Instalado Pacote StoqDrivers

	echo -e "╔═══════════════════════════════╗"
	echo -e "║ Instalando pacote StoqDrivers ║"
	echo -e "╚═══════════════════════════════╝"
	cd $instpasta
	dpkg -i $stoqdrivers
	sleep 3

	# Instalando Pacote ErrorHandler

	echo -e "╔════════════════════════════════╗"
	echo -e "║ Instalando pacote ErrorHandler ║"
	echo -e "╚════════════════════════════════╝"
	cd $instpasta
	dpkg -i $errorhandler
	sleep 3

	# Instalado Pacote XlUtils

	echo -e "╔═══════════════════════════╗"
	echo -e "║ Instalando pacote XlUtils ║"
	echo -e "╚═══════════════════════════╝"
	cd $instpasta
	dpkg -i $xlutils
	sleep 3

	# Instalado Pacote Python-Sqlalchemy

	echo -e "╔═════════════════════════════════════╗"
	echo -e "║ Instalando pacote Python-Sqlalchemy ║"
	echo -e "╚═════════════════════════════════════╝"
	cd $instpasta
	dpkg -i $pysqlalchemy
	dpkg -i $pysqlalchemydoc
	sleep 3

	# Instalado Pacote Python-Serial

	echo -e "╔═════════════════════════════════╗"
	echo -e "║ Instalando pacote Python-Serial ║"
	echo -e "╚═════════════════════════════════╝"
	cd $instpasta
	dpkg -i $pyserial
	sleep 3

	# Instalado Pacote Python-Elixir

	echo -e "╔════════════════════════════════╗"
	echo -e "║ Instalando pacote Python-Elixr ║"
	echo -e "╚════════════════════════════════╝"
	cd $instpasta
	dpkg -i $elixir
	sleep 3

	# Instalado Pacote Python-Ordereddict

	echo -e "╔══════════════════════════════════════╗"
	echo -e "║ Instalando pacote Python-Ordereddict ║"
	echo -e "╚══════════════════════════════════════╝"
	cd $instpasta
	dpkg -i $pyordereddict
	sleep 3

	# Instalado Pacote SigUtils
	if [[ $versao == '16.04' ]];then
		echo -e "╔══════════════════════════════════╗"
		echo -e "║ Instalando pacote sigutils-2.4.9 ║"
		echo -e "╚══════════════════════════════════╝"
		cd $instpasta
		tar xfvz sigutils-2.4.9.tar.gz
		cd sigutils-2.4.9/
		python setup.py install
	elif [[ $versao == '18.04' ]];then
		echo -e "╔═══════════════════════════════════╗"
		echo -e "║ Instalando pacote SigUtils-2.4.14 ║"
		echo -e "╚═══════════════════════════════════╝"
		cd $instpasta
		tar xfvz SigUtils-2.4.14.tar.gz
		cd SigUtils-2.4.14/
		python setup.py install
	elif [[ $versao == '14.04' ]];then
		echo "| Versão 14 do Linux  |"
		echo "| Caixa desatualizado |"
		echo "| Processo encerrado  |"
		exit
	else
		echo "Algo errado na verão do Sistema Linux"
		sigutilsni=1
	fi

	# Instalado Pacote Python-NF-e
	echo -e "╔═════════════════════════════════════╗"
	echo -e "║ Instalando pacote pythonnfe $vnfce ║"
	echo -e "╚═════════════════════════════════════╝"
	cd $instpasta
	tar xfvz $pythonnfe
	cd $instpasta/nfe-$vnfce/
	python setup.py install
	sleep 3

	# Instalado Pacote SigPDV3.1-NFC-e
	echo -e "╔═══════════════════════════════════════╗"
	echo -e "║ Instalando pacote Sig Frente 3.1.21L3 ║"
	echo -e "╚═══════════════════════════════════════╝"
	cd $instpasta
	dpkg -i $sigfrente
	sleep 3

	# Atualiza PDV para ultima versão
	echo -e "╔════════════════════════════════════════════════════════════════╗"
	echo -e "║ Baixando TAR do sigpdv atualizadado SigFrente e descampactando ║"
	echo -e "╚════════════════════════════════════════════════════════════════╝"
	sleep 3
	cd $instpasta
	wget $dlpadrao/sigpdv_$versaopdv.tar.gz
	cp sigpdv_$versaopdv.tar.gz /usr/local/
	cd /usr/local/
	tar xfvz sigpdv_$versaopdv.tar.gz
	rm -rf sigpdv_$versaopdv.tar.gz
	chown caixa:caixa /usr/local/sigpdv/ -R

	# Bloqueando Atualização dos Pacotes Necessários para o SigFrente
	apt-mark hold python-sqlalchemy
	apt-mark hold python-sqlalchemy-doc
	apt-mark hold python-sqlalchemy-ext
	apt-mark hold python-elixir
	apt-mark hold python-serial

	# Criando Link Simbólico da SigPdv

	ln -s /usr/local/sigpdv /usr/local/lib/python2.7/dist-packages/sigpdv

	# Criando Atalho Desktop
	if [ -e /home/caixa/ ];then
		cp /usr/share/applications/SigPDV.desktop /home/caixa/Área\ de\ Trabalho/ && chmod 777 /home/caixa/Área\ de\ Trabalho/SigPDV.desktop
		cp /usr/share/applications/PdvConfig.desktop /home/caixa/Área\ de\ Trabalho/ && chmod 777 /home/caixa/Área\ de\ Trabalho/PdvConfig.desktop
		cp /usr/share/applications/terminator.desktop /home/caixa/Área\ de\ Trabalho/ && chmod 777 /home/caixa/Área\ de\ Trabalho/terminator.desktop
	elif [ -e /home/sig/ ];then
		cp /usr/share/applications/SigPDV.desktop /home/sig/Área\ de\ Trabalho/ && chmod 777 /home/sig/Área\ de\ Trabalho/SigPDV.desktop
		cp /usr/share/applications/PdvConfig.desktop /home/sig/Área\ de\ Trabalho/ && chmod 777 /home/sig/Área\ de\ Trabalho/PdvConfig.desktop
		cp /usr/share/applications/terminator.desktop /home/sig/Área\ de\ Trabalho/ && chmod 777 /home/sig/Área\ de\ Trabalho/terminator.desktop
	else
		echo -e "╔════════════════════════════════════════════╗"
		echo -e "║ Não foi possível criar atalhos no Desktop! ║"
		echo -e "╚════════════════════════════════════════════╝"
		sleep 3
	fi

	# Criando Arquivos Necessários

	cd /var/cache
	mkdir ChavesCliSiTef
	chmod 1777 ChavesCliSiTef/

	if [[ -e /recebe/ ]];then
		echo " "
	else
		cd /
		mkdir recebe
		chmod 777 recebe/ -R
	fi

	echo /usr/local/sigpdv/sigtef/lib_x86_64/ >> /etc/ld.so.conf
	ldconfig
	echo UseDNS no >> /etc/ssh/sshd_config

	# Criando Arquivo de Configuração para "TMP"
	cd /etc/tmpfiles.d/
	touch clisitef.conf
	echo "L /tmp/ChavesCliSiTef 1777 - - - /var/cache/ChavesCliSiTef" >> clisitef.conf

	# Alterando o Network-Time do Sistema
	timedatectl set-local-rtc 0
	timedatectl set-timezone America/Sao_Paulo
	timedatectl set-ntp true

	# Adicionando usuário caixa ou sig ao grupo dialout
	if [ -e /home/caixa/ ];then
		adduser caixa dialout
		sudo usermod -aG dialout caixa
	elif [ -e /home/sig/ ];then
		adduser sig dialout
		sudo usermod -aG dialout sig
	else
		echo -e "╔════════════════════════════════════════════════════════════════════╗"
		echo -e "║ Não foi possível adicionar usuários caixa ou sig no grupo dialout! ║"
		echo -e "╚════════════════════════════════════════════════════════════════════╝"
		sleep 3
	fi

	echo -e "╔════════════════════════════════════════════════════════════════╗"
	echo -e "║ Baixando outros scripts necessários para a instalação do caixa ║"
	echo -e "╚════════════════════════════════════════════════════════════════╝"
	sleep 3
	cd /recebe/
	wget $dltxt/rustdesk.sh
	wget $dltxt/tef_v2.1.3.sh
	wget $dltxt/bkp.sh
	wget $dltxt/cria_recebe.sh
	wget $dltxt/dl_sigimages.sh
	wget $dltxt/start-sigpdv

	cd $instpasta

	mv start-sigpdv /usr/bin/
	mv sig.jpg /usr/share/xfce4/backdrops/ && chmod 777 /usr/share/xfce4/backdrops/sig.jpg
	mv menu-sig.png /usr/share/pixmaps/ && chmod 777 /usr/share/pixmaps/menu-sig.png

	clear
	echo "╔══════════════════════╗"
	echo "║ INSTALAÇÃO CONCLUIDA ║"
	echo "╚══════════════════════╝"
	if [[ $sigutilsni == '1' ]];then
		echo "╔═════════════OBS=════════════╗"
		echo "║ SigUtils não foi instalado! ║"
		echo "╚═════════════════════════════╝"
	fi
	exit

else
	clear
	echo " "
    echo "╔══════════════════════════════════════════════╗"
    echo "║ Execute este aplicatvo como Root, por favor. ║"
    echo "╚══════════════════════════════════════════════╝"
    exit
fi
