#!/bin/bash

#author:Cristiano Siqueira
#descricao:Automatiza a atualização do Supervisor/Caixa, baixando os pacotes, modulos e a versão do ERP mais atualizada.
#Revisao:

erro_opcao(){
    clear
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║              Você digitou uma opção erra!                ║"
    echo "║  Por favor, reinicie o processo e responda corretamente. ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    exit
}

lerpfvcfg(){
    while [ $linha -le 19 ]
    do
      cat -n /usr/local/sigpdv/pdvconfig.cfg | grep -n ^ | grep ^$linha: | cut -d: -f2
      linha=$(( $linha + 1 ))
    done
}

versaopacotes() { #imprime as versões dos pacotes instalados
    local width=26
    local padding=$((width - 2))
    echo "╔══Pacotes Instalados══╗"
    python << EOF
# -*- coding: utf-8 -*-
import pynfe
print "║ PyNFe: {}".format(pynfe.__version__).ljust($padding) + " ║"
import SigUtils
print "║ SigUtils: {}".format(SigUtils.__version__).ljust($padding) + " ║"

with open('/usr/local/sigerp/adm/__openerp__.py', 'r') as f:
    for line in f:
        if "'version': '" in line:
            version = line.split("'")[3]
            print "║ SigERP: {}".format(version).ljust($padding) + " ║"

import subprocess
sped_version = subprocess.check_output("pip list 2>/dev/null | grep sped", shell=True).strip().split()[1]
print "║ Sped: {}".format(sped_version).ljust($padding) + " ║"
EOF
    echo "╚══════════════════════╝"
}

upostgres='postgres'
uopenerp='openerp'
pgdumpcx='pg_dump --host localhost --port 5432 --username "$upostgres" --role "$upostgres" --format custom --blobs --verbose --file $pastapadrao/sigpdv.dump $bpdv'
pgdumpsupervisor='pg_dump --host localhost --port 5432 --username "$uopenerp" --role "$uopenerp" --format custom --blobs --verbose --file $pastapadrao/$spdv.dump $spdv'
sobebase='sudo -u openerp openerp-server -uall -c /etc/openerp-server.conf -d $spdv --stop-after-init'
databkp=$(date "+%d%m%Y")
user=`whoami`
dlpadrao='download.sigsolucoes.net.br/produtos/crss/erp'
pastapadrao='/recebe/erpbkp'
pyinstall='python setup.py install'
PyNFe=5.0.22
SigUtils=2.4.14
sped=1.36.2
sigerp=2408.2

if [[ $user == 'root' ]];then
    cd /recebe/
    mkdir erpbkp
    chmod 777 erpbkp/ -R
    cd erpbkp

    wget $dlpadrao/PyNFe-$PyNFe.tar.gz
    wget $dlpadrao/SigUtils-$SigUtils.tar.gz
    wget $dlpadrao/sped-$sped.tar.gz
    wget $dlpadrao/sigerp_$sigerp.tar.gz

    tar xfvz PyNFe-$PyNFe.tar.gz
    tar xfvz SigUtils-$SigUtils.tar.gz
    tar xfvz sped-$spedtar.gz

    cd $pastapadrao/PyNFe-$PyNFe/ && $pyinstall
    cd $pastapadrao/SigUtils-$SigUtils/ && $pyinstall
    cd $pastapadrao/sped-$sped/ && $pyinstall

    cd $pastapadrao/
    cp sigerp_$sigerp.tar.gz /usr/local/ && cd /usr/local
    mv sigerp sigerp_$databkp && tar xfvz sigerp_$sigerp.tar.gz && rm -rf sigerp_$sigerp.tar.gz

    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

    grep 'db_password' '/etc/openerp-server.conf' | awk '{print$3}'
    psql -U openerp -l
    echo -e "╔════════════════════════════════════════╗"
    echo -e "║ Digite o nome da base que deseja subir ║"
    echo -e "╚════════════════════════════════════════╝"
    read -p "Qual o nome do banco do Caixa para backup? R: " bpdv
    read -p "Qual o nome do banco do Supervisor para backup? R: " spdv
    echo " "

    lerpfvcfg

    echo " "
    echo "Criando dump sigpdv. . ."
    echo " "
    sleep 3

    $pgdumpcx

    lerpfvcfg
    echo " "
    echo "Criando dump do supervisor. . ."
    echo " "
    sleep 3

    $pgdumpsupervisor

    echo " "
    echo "Arquivos salvos na pasta: $pastapadrao:"
    echo " "
    ls -lha $pastapadrao/
    sleep 3

    $sobebase

    echo -e "╔══════════════════════╗"
    echo -e "║ Processo finalizado! ║"
    echo -e "╚══════════════════════╝"

    exit

else

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