#!/bin/bash
##By: RAFAEL RIBEIRO
##Modificado por: Christian Tosta em 14/12/2016 15:35 BRST.
##Revision: RAFAEL BORGES E CAIO SANTOS
##Atualizado por: CRISTIANO RODRIGUES SIQUEIRA SOARES
##Nova revisão:

user=`whoami`
versao=$(lsb_release -r -s)

if [[ $user == "root" ]]; then

	# Versão atualizada dos pacotes
	mkdir /tmp/install_sigerp/
	chmod 777 /tmp/install_sigerp/
	cd /tmp/install_sigerp/
	touch install_log_sigerp.log
	rm -rf update
	apt-get update -y

	log='/tmp/install_sigerp/install_log_sigerp.log'

	#wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/releases/sigerp/7.0/update >> $log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/releases/logo/sig.jpg
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/releases/logo/menu-sig.png
	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

	openerp=`cat /tmp/install_sigerp/update | grep -i openerp | cut -d"=" -f2`
	pythonnfe=`cat /tmp/install_sigerp/update | grep -i nfe | cut -d"=" -f2`
	pythonsped=`cat /tmp/install_sigerp/update | grep -i sped | cut -d"=" -f2`
	sigutils=`cat /tmp/install_sigerp/update | grep -i sigutils | cut -d"=" -f2`
	sigerp=`cat /tmp/install_sigerp/update | grep -i sigerp | cut -d"=" -f2`
	geraldo='geraldo_0.4.10-stable-sig.tar.gz'
	pyxmlsec='python-pyxmlsec_0.3.1-1openhouse2_amd64.deb'
	xlutils='python-xlutils_1.5.1-1_all.deb'
	vpostgresql='13'

	#Arquivos TAR.GZ
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/openerp-7.0.2310.1.tar.gz >> $log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/sigutils-2.4.11.tar.gz >> $log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/sped-1.36.2.tar.gz >> $log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/sigerp_2404-1.tar.gz >>$log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/geraldo_0.4.10-stable-sig.tar.gz >> $log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/PyNFe-5.0.19.tar.gz >> $log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/signxml.tar.gz >> $log

	#Arquivos DEB
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/python-pyxmlsec_0.3.1-1openhouse2_amd64.deb >> $log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/python-xlutils/python-xlutils_1.5.1-1_all.deb >> $log

	#Arquivos de configuração do OpenERP
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/openerp-server.conf >> $log
	wget -c --progress=bar:force download.sigsolucoes.net.br/produtos/crss/erp/openerp-server >> $log
	chmod -R 777 /tmp/install_sigerp

	if [ -e openerp-7.0.2310.1.tar.gz        ] &&
	   [ -e sigutils-2.4.11.tar.gz           ] &&
	   [ -e sped-1.36.2.tar.gz               ] &&
	   [ -e sigerp_2404-1.tar.gz             ] &&
	   [ -e geraldo_0.4.10-stable-sig.tar.gz ] &&
	   [ -e PyNFe-5.0.19.tar.gz              ] &&
	   [ -e signxml.tar.gz                   ];then

		echo "╔════════════════════════════════╗"
		echo "║ Download efetuado com sucesso! ║"
		echo "╚════════════════════════════════╝"
		echo "Download efetuado com sucesso!" >> $log
	else
		echo "╔════════════════════════════════════════╗"
		echo "║ Não foi possível efetuar o download... ║"
		echo "╚════════════════════════════════════════╝"
		echo "Não foi possível efetuar o download..." >> $log
		echo "╔════════════════════════════════════════════════════╗"
		echo "║ Verifique se os links de downloads estão corretos. ║"
		echo "╚════════════════════════════════════════════════════╝"
		echo "Verifique se os links de downloads estão corretos." >> $log
		exit
	fi
	
	# Instalando Pacotes Necessários
	echo "╔═════════════════════════════╗"
	echo "║ Obtendo pacotes Necessários ║"
	echo "╚═════════════════════════════╝"
	echo 'Obtendo pacotes Necessários...' >> $log
	apt-get update -y
	apt-get install vim -y
	apt-get install openssh-server -y
	apt-get install terminator -y

	# Configurações Postgresql

	#apt-get 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-get update -y
	apt-get install postgresql-13 postgresql-client-13 -y

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

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

	echo -e "\n\nconfiguração do postgres alterado para utilização do Sigerp" >> $log
	echo "╔═════════════════════════════════════════════════════════════╗"
	echo "║ Alterado configuração do postgres para utilização do Sigerp ║"
	echo "╚═════════════════════════════════════════════════════════════╝"
	cd /etc/postgresql/13/main/ >> $log
	sed -i "s/#listen_addresses = 'localhost'/listen_addresses = '*'/g" postgresql.conf
	sed -i "s/porta = 5433/porta = 5432/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
	sed -i "s/host    replication     all             0.0.0.0\/0/#host    replication     all             0.0.0.0\/0/g" pg_hba.conf
	sed -i "s/host    replication     all             ::1\/128/#host    replication     all             ::1\/128/g" pg_hba.conf
	sed -i -e "s/local   all             postgres                                trust/local   all             postgres                                trust\nlocal   all             openerp                                 trust/g" pg_hba.conf

	/etc/init.d/postgresql stop
	/etc/init.d/postgresql start
	createdb -U postgres -E utf8 sigpdv -h localhost
	/etc/init.d/postgresql reload
	/etc/init.d/postgresql restart

	echo -e "\n\nCriando usuario no banco de dados posgresql" >> $log
	echo -e "╔═════════════════════════════════════════════╗"
	echo -e "║ Criando usuario no banco de dados PosgreSQL ║"
	echo -e "╚═════════════════════════════════════════════╝"

	createuser -U postgres --createdb -P openerp

	echo " "
	echo -e "╔═══════════════════════════════════════════╗"
	echo -e "║ Iniciando instalação de pacotes do SigERP ║"
	echo -e "╚═══════════════════════════════════════════╝"
	sleep 3
	echo " "

	# Instalação Pacotes do SigERP
	apt install python-pip -y #Deve se instalar o python-pip antes de qualquer pacote, para prevenir erros na instalação
	apt install python-apt-get -y
	apt install htop -y
	apt install python-lxml -y
	apt install python-mako -y
	apt install python-dateutil -y
	apt install python-psycopg2 -y
	apt install python-jwt -y
	apt install python-dnspython -y
	apt install python-numpy -y
	apt install python-pychart -y
	apt install python-pydot -y
	apt install python-tz -y
	apt install python-reportlab -y
	apt install python-yaml -y
	apt install python-vobject -y
	apt install python-dev -y
	apt install libmysqlclient-dev -y
	apt install pgadmin3 -y
	apt install python-setuptools -y
	apt install python-mysqldb -y
	apt install python-beautifulsoup -y
	apt install python-m2crypto -y
	apt install python-libxml2 -y
	apt install python-feedparser -y
	apt install python-gdata -y
	apt install python-openid -y
	apt install python-webdav -y
	apt install python-vatnumber -y
	apt install python-werkzeug -y
	apt install python-xlwt -y #Deve ser instalado antes do xlrd-1.2.0
	pip install xlrd==1.2.0 #A versão deve ser 1.2.0
	apt install xltils -y
	apt install python-zsi -y
	apt install python-ldap -y
	apt install python-babel -y
	apt install python-mock -y
	apt install python-jinja2 -y
	apt install python-docutils -y
	apt install python-gevent -y
	apt install xmlsec1 -y
	apt install libxmlsec1-dev -y
	apt install python-unittest2 -y
	apt install python-simplejson -y
	apt install python-psutil -y
	apt install python-cups -y
	apt install python-requests -y
	apt install python-qrcode -y
	apt install python-zeep -y
	apt install samba* -y
	apt install python3-smbc -y
	apt install python-pandas -y
	apt install -f -y

	easy_install -f http://www.pythonware.com/products/pil/ Imaging

	# Instalado Pacote PyXmlSec

	echo -e "\n\nInstalando pacote PyXmlSec" >> $log
	echo -e "╔════════════════════════════╗"
	echo -e "║ Instalando pacote PyXmlSec ║"
	echo -e "╚════════════════════════════╝"
	echo -e "cd /tmp/install_sigerp/" >> $log
	cd /tmp/install_sigerp/ >> $log
	dpkg -i python-pyxmlsec_0.3.1-1openhouse2_amd64.deb >> $log

	# Instalado Pacote XlUtils

	echo -e "\n\nInstalando pacote XlUtils" >> $log
	echo -e "╔═══════════════════════════╗"
	echo -e "║ Instalando pacote XlUtils ║"
	echo -e "╚═══════════════════════════╝"
	cd /tmp/install_sigerp/ >> $log
	dpkg -i python-xlutils_1.5.1-1_all.deb >> $log

	# Instalando Pacote Geraldo-Stable

	echo -e "\n\nInstalando pacote Geraldo-Stable" >> $log
	echo -e "╔══════════════════════════════════╗"
	echo -e "║ Instalando pacote Geraldo-Stable ║"
	echo -e "╚══════════════════════════════════╝"
	cd /tmp/install_sigerp/ >> $log
	tar xfvz geraldo_0.4.10-stable-sig.tar.gz >> $log
	cd Geraldo-0.4.10-stable-sig >> $log
	python setup.py install >> $log

	# Instalado Pacote atualizado Openerp

	echo -e "\n\nInstalando pacote openerp-server" >> $log
	echo -e "╔══════════════════════════════════╗"
	echo -e "║ Instalando pacote openerp-server ║"
	echo -e "╚══════════════════════════════════╝"
	cd /tmp/install_sigerp/ >> $log
	tar xfvz openerp-7.0.2310.1.tar.gz >> $log
	cd openerp-7.0.2310.1 >> $log
	python setup.py install >> $log

	# Instalado Pacote atualizado Python-Sped

	echo -e "\n\nInstalando pacotes do sped" >> $log
	echo -e "╔════════════════════════════╗"
	echo -e "║ Instalando pacotes do sped ║"
	echo -e "╚════════════════════════════╝"
	cd /tmp/install_sigerp/ >> $log
	tar xfvz sped-1.36.2.tar.gz >> $log
	cd sped-1.36.2 >> $log
	python setup.py install >> $log

	# Instalado Pacote atualizado SigUtils

	echo -e "\n\nInstalando SigUtils" >> $log
	echo -e "╔═════════════════════╗"
	echo -e "║ Instalando SigUtils ║"
	echo -e "╚═════════════════════╝"
	cd /tmp/install_sigerp/ >> $log
	tar xfvz sigutils-2.4.11.tar.gz >> $log
	cd sigutils-2.4.11
	python setup.py install >> $log
	
	# Instalado Pacote atualizado PyNFe

	echo -e "╔═════════════════════════════════╗"
	echo -e "║ Instalando pacotes PyNFe-5.0.19 ║"
	echo -e "╚═════════════════════════════════╝"
	sleep 3
	cd /tmp/install_sigerp/
	tar xfvz PyNFe-5.0.19.tar.gz
	cd PyNFe-5.0.19
	python setup.py install

	echo -e "╔════════════════════════════════╗"
	echo -e "║ Instalando modulos necessários ║"
	echo -e "╚════════════════════════════════╝"
	sleep 3
	#apt -y install python-pip
	pip install html
	pip install signxml==2.8.1
	apt -y install python2-dev
	apt -y install libgl1-mesa-glx
	apt -y install python-sqlalchemy
	pip install eight

	echo -e "╔═══════════════════════════╗"
	echo -e "║ Atualizando pasta signxml ║"
	echo -e "╚═══════════════════════════╝"
	sleep 3
	cd /tmp/install_sigerp/
	tar xfvz signxml.tar.gz
	cp -r -v signxml /usr/local/lib/python2.7/dist-packages/

	# Configurações Openerp

	echo -e "\n\nCriando usuario openerp" >> $log
	echo -e "╔═════════════════════════╗"
	echo -e "║ Criando usuario openerp ║"
	echo -e "╚═════════════════════════╝"
	useradd openerp >> $log

	echo -e "\n\nConfigurando o openerp-server como serviço" >> $log
	echo -e "╔════════════════════════════════════════════╗"
	echo -e "║ Configurando o openerp-server como serviço ║"
	echo -e "╚════════════════════════════════════════════╝"
	echo -e "Copiando script de inicialização" >> $log
	cp /tmp/install_sigerp/openerp-server /etc/init.d/ >> $log
	chmod +x /etc/init.d/openerp-server >> $log
	echo -e "\n\nCopiando arquivo de configuração" >> $log
	cp /tmp/install_sigerp/openerp-server.conf /etc >> $log
	echo -e "\n\nMudando permissão dos arquivos de configuração para usuário openerp" >> $log
	chown openerp:adm /etc/openerp-server.conf >> $log
	echo -e "\n\nCriando arquivos de logs" >> $log
	mkdir /var/log/openerp/ >> $log
	touch /var/log/openerp/openerp-server.log >> $log
	chmod 777 /var/log/openerp >> $log
	chmod 777 /var/log/openerp/* >> $log
	chown openerp:openerp /var/log/openerp/* >> $log
	chown openerp:openerp /var/log/openerp >> $log
	update-rc.d openerp-server defaults >> $log

	# Instalado Pacote atualizado SigERP

	echo -e "Criando diretório para modulos sig" >> $log
	echo -e "╔════════════════════════════════════╗"
	echo -e "║ Criando diretório para modulos sig ║"
	echo -e "╚════════════════════════════════════╝"
	mkdir /usr/local/
	chown root:openerp /usr/local/sigerp
	chmod 775 /usr/local/sigerp
	cd /usr/local/
	cp /tmp/install_sigerp/sigerp_2404-1.tar.gz .
	tar xfvz sigerp_2404-1.tar.gz

	echo -e "╔═══════════════════════════════════════════╗"
	echo -e "║ Reiniciando serviços Postgresql e OpenERP ║"
	echo -e "╚═══════════════════════════════════════════╝"
	sleep 2

	/etc/init.d/openerp-server stop
	/etc/init.d/postgresql stop

	/etc/init.d/postgresql start
	/etc/init.d/openerp-server start

	sleep 3
	clear
	echo "╔══════════════════════╗"
	echo "║ INSTALAÇÃO CONCLUIDA ║"
	echo "╚══════════════════════╝"
	echo " "
	echo " "
	echo " "

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