#configuração

#configuracao
elotech_d=/elotech
web_d=${elotech_d}/web
api_v="1.51.0"
tomcat_v="9.0.5"
transp_v="2.158.0"
trib_v="3.125.0"
unico_v="4.5.0"
protoc_v="3.350.1"
report_server_v="2.55.0"

#Espelho
mirror=repos.bettertech.com.br

install_essential_package()
{

yum install -y wget zip unzip vim tar
yum install -y fontconfig xorg-x11-font-utils

}

install_ms_fonts()
{
    yum install -y https://downloads.sourceforge.net/project/mscorefonts2/rpms/msttcore-fonts-installer-2.6-1.noarch.rpm
}

init_db_config()
{

dbconfig=${elotech_d}/dbconfig.ini

if [ ! -f "$dbconfig" ]; then
    echo "Infome o IP do Banco de Dados"
    read -p "host:" pg_host
    
    #dbconfig
    echo "[dbconfig]" > $dbconfig
    echo "aise.appinstancetype=Única (Single)" >> $dbconfig
    echo "aise.db=elotech" >> $dbconfig
    echo "aise.dbtype=Postgres" >> $dbconfig
    echo "aise.host=${pg_host}" >> $dbconfig
    echo "aise.password=46234f31583858355d3844375d35" >> $dbconfig
    echo "aise.user=aise" >> $dbconfig
    echo "backup.password=46234f315838" >> $dbconfig
    echo "backup.user=elotech" >> $dbconfig
    echo "compras.db=elotech" >> $dbconfig
    echo "compras.dbtype=Postgres" >> $dbconfig
    echo "compras.host=${pg_host}" >> $dbconfig
    echo "compras.password=46234f315838583544385e375b355131" >> $dbconfig
    echo "compras.user=apice" >> $dbconfig
    echo "contabilidade.db=elotech" >> $dbconfig
    echo "contabilidade.dbtype=Postgres" >> $dbconfig
    echo "contabilidade.host=${pg_host}" >> $dbconfig
    echo "contabilidade.password=46234f3158385a355b3859374c355531" >> $dbconfig
    echo "contabilidade.user=siscop" >> $dbconfig
    echo "datasnap.dsport=8097" >> $dbconfig
    echo "datasnap.httpport=localhost" >> $dbconfig
    echo "eloarquivo.db=elotech" >> $dbconfig
    echo "eloarquivo.dbtype=Postgres" >> $dbconfig
    echo "eloarquivo.host=${pg_host}" >> $dbconfig
    echo "eloarquivo.password=46234f3158385835463846374d355d3147345a35" >> $dbconfig
    echo "eloarquivo.user=eloarquivo" >> $dbconfig
    echo "protocolo.db=elotech" >> $dbconfig
    echo "protocolo.dbtype=Postgres" >> $dbconfig
    echo "protocolo.host=${pg_host}" >> $dbconfig
    echo "protocolo.password=46234f3158384935463858374c355b315234" >> $dbconfig
    echo "protocolo.user=protocolo" >> $dbconfig
    echo "sigelo.db=elotech" >> $dbconfig
    echo "sigelo.dbtype=Postgres" >> $dbconfig
    echo "sigelo.host=${pg_host}" >> $dbconfig
    echo "sigelo.password=50234a3150385c3558385837" >> $dbconfig
    echo "sigelo.user=sigeloam" >> $dbconfig
    echo "unico.db=elotech" >> $dbconfig
    echo "unico.dbtype=Postgres" >> $dbconfig
    echo "unico.host=${pg_host}" >> $dbconfig
    echo "unico.password=46234f3158384c355a385e375b355b31" >> $dbconfig
    echo "unico.user=unico" >> $dbconfig
    echo "unicoserver.host=localhost:8761" >> $dbconfig
fi

}

apps_dir_create()
{
  sudo useradd -m -U -d /elotech -s /bin/false elotech
  mkdir -p ${elotech_d}/web
  mkdir -p ${elotech_d}/jdbc
  chown elotech:elotech /elotech -R
  init_db_config
}

install_java(){

jre_file="jre-8u251-linux-x64.tar.gz"

if [ ! -f "/usr/lib/java-1.8x-jre/bin/java" ]; then

  echo "Instalando java"
  #java
  wget --no-check-certificate https://${mirror}/unix/java/${jre_file} -P /tmp
  sudo tar xvzf /tmp/${jre_file} -C /tmp
  rm -rf /tmp/${jre_file}
  sudo mv /tmp/jre1* /tmp/java-1.8x-jre
  sudo mv /tmp/java-1.8x-jre /usr/lib/
  sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/java-1.8x-jre/bin/java" 1
  sudo update-alternatives --display java
  java -version

fi

}

install_java11() {

  jre_file="open-jdk-11.0.11+9-linux-x64.tar.gz"
  mirror="repos.bettertech.com.br"

  if [ ! -f "/usr/lib/adopt-open-jdk/11/bin/java" ]; then

    echo "Instalando Java 11..."
    
    # Baixa o pacote JDK 11
    wget --no-check-certificate https://${mirror}/unix/java/${jre_file} -P /tmp

    # Extrai o arquivo baixado
    sudo tar xvzf /tmp/${jre_file} -C /tmp

    # Garante que o diretório temporário existe antes de usá-lo
    if [ ! -d "/tmp/adopt-open-jdk" ]; then
      sudo mkdir -p /tmp/adopt-open-jdk
    fi

    # Renomeia o JDK extraido
    sudo mv /tmp/jdk-*/ /tmp/adopt-open-jdk/11
	# Move o JDK extraído para o diretório correto
    sudo mv /tmp/adopt-open-jdk/11 /usr/lib/adopt-open-jdk

    # Configura o Java 11 como uma alternativa
    sudo update-alternatives --install "/usr/bin/java11" "java11" "/usr/lib/adopt-open-jdk/11/bin/java" 2

    # Mostra as alternativas configuradas
    sudo update-alternatives --display java11

    # Remove diretório temporário
    rm -rf /tmp/adopt-open-jdk

    echo "Instalação concluída. Use 'sudo update-alternatives --config java' para selecionar a versão padrão."
  else
    echo "Java 11 já está instalado."
  fi
}



install_java17() {

  jre_file="open-jdk-17.0.14-linux-x64.tar.gz"
  mirror="repos.bettertech.com.br"

  if [ ! -f "/usr/lib/adopt-open-jdk/17/bin/java" ]; then

    echo "Instalando Java 17..."
    
    # Baixa o pacote JDK 17
    wget --no-check-certificate https://${mirror}/unix/java/${jre_file} -P /tmp

    # Extrai o arquivo baixado
    sudo tar xvzf /tmp/${jre_file} -C /tmp

    # Garante que o diretório temporário existe antes de usá-lo
    if [ ! -d "/tmp/adopt-open-jdk" ]; then
      sudo mkdir -p /tmp/adopt-open-jdk
    fi

    # Renomeia o JDK extraido
    sudo mv /tmp/jdk-*/ /tmp/adopt-open-jdk/17
	# Move o JDK extraído para o diretório correto
    sudo mv /tmp/adopt-open-jdk/17 /usr/lib/adopt-open-jdk

    # Configura o Java 17 como uma alternativa
    sudo update-alternatives --install "/usr/bin/java17" "java17" "/usr/lib/adopt-open-jdk/17/bin/java" 3

    # Mostra as alternativas configuradas
    sudo update-alternatives --display java17
	
	rm -rf /tmp/adopt-open-jdk

    echo "Instalação concluída. Use 'sudo update-alternatives --config java' para selecionar a versão padrão."
  else
    echo "Java 17 já está instalado."
  fi
}



install_nginx()
{

if [ ! -f /etc/nginx/nginx.conf ]; then
  sed -ri "s/SELINUX=enforcing/SELINUX=disabled/" /etc/selinux/config
  setenforce 0

  nginx_repo=/etc/yum.repos.d/nginx.repo

  echo '[nginx]' >> $nginx_repo
  echo 'name=nginx repo' >> $nginx_repo
  echo 'baseurl=http://nginx.org/packages/centos/$releasever/$basearch/' >> $nginx_repo
  echo 'gpgcheck=0' >> $nginx_repo
  echo 'enabled=1' >> $nginx_repo
  
  sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048

  sudo yum install -y epel-release net-tools yum-utils nginx
  
  sudo yum install -y certbot
  
  rm -rf /etc/nginx/conf.d
  
  sudo mkdir -p /var/lib/letsencrypt/.well-known
  sudo chgrp nginx /var/lib/letsencrypt
  sudo chmod g+s /var/lib/letsencrypt
  
  sudo mkdir /etc/nginx/snippets

  systemctl enable nginx
fi

}

config_elo_nginx()
{

if [ ! -f "/etc/nginx/elotech.conf" ]; then

  wget --no-check-certificate https://${mirror}/unix/release/nginx/nginx-unix.zip -P /tmp

  yes | unzip /tmp/nginx-unix.zip -d /etc/nginx/

  systemctl reload nginx

fi

chown nginx:nginx ${elotech_d} -R

# adiciona o nginx ao grupo elotech
sudo usermod -aG elotech nginx

}

install_oxy_api()
{

if [ ! -f "${web_d}/server/api/elotech-api.jar" ]; then
  #download oxy api
  wget --no-check-certificate https://${mirror}/unix/release/api/api-$api_v.zip -P /tmp
  yes | unzip /tmp/api-$api_v.zip -d ${web_d}
  
  chown elotech:elotech  /elotech -R

  systemctl enable elotech-api.service
fi

}

install_oxy_portal_transp(){

install_ms_fonts

if [ ! -f "${web_d}/server/portaltransparencia/portaltransparencia.jar" ]; then

  #download oxy portal transparencia
  wget --no-check-certificate https://${mirror}/unix/release/transparencia/portal-transparencia-${transp_v}.zip -P /tmp

  yes | unzip /tmp/portal-transparencia-${transp_v}.zip -d ${web_d}
  
  chown elotech:elotech  /elotech -R

  systemctl enable elotech-portal-transparencia.service

fi

}

install_oxy_unico()
{

if [ ! -f "${web_d}/server/unico/unico.jar" ]; then

  #download oxy unico
  wget --no-check-certificate https://${mirror}/unix/release/unico/unico-${unico_v}.zip -P /tmp

  yes | unzip /tmp/unico-${unico_v}.zip -d ${web_d}
  
  chown elotech:elotech  /elotech -R

  systemctl enable elotech-unico.service

fi


}

install_oxy_portal_contrib()
{

install_ms_fonts

if [ ! -f "${web_d}/server/tributos/tributos.jar" ]; then

  #download oxy portal contribuinte
  wget --no-check-certificate https://${mirror}/unix/release/portalcontribuinte/portal-contribuinte-${trib_v}.zip -P /tmp

  yes | unzip /tmp/portal-contribuinte-${trib_v}.zip -d ${web_d}
  
  chown elotech:elotech  /elotech -R

  systemctl enable elotech-portal-contribuinte.service

fi


}

install_oxy_protocolo()
{

if [ ! -f "${web_d}/server/protocolo/protocolo.jar" ]; then

  #download oxy protocolo
  wget --no-check-certificate https://${mirror}/unix/release/protocolo/protocolo-${protoc_v}.zip -P /tmp

  yes | unzip /tmp/protocolo-${protoc_v}.zip -d ${web_d}
  
  chown elotech:elotech  /elotech -R

  systemctl enable elotech-protocolo.service

fi


}

install_oxy_report_server(){

if [ ! -f "${web_d}/server/report-server/report-server.jar" ]; then

  #download oxy report-server
  wget --no-check-certificate https://${mirror}/unix/release/reportserver/report-server-${report_server_v}.zip -P /tmp

  yes | unzip /tmp/report-server-${report_server_v}.zip -d ${web_d}
  
  chown elotech:elotech  /elotech -R

  systemctl enable elotech-report-server.service

fi


}

install_tomcat()
{

if [ ! -d "/etc/tomcat/default" ]; then

generate_random_string() {
    openssl rand -base64 12 | tr -dc 'a-zA-Z0-9' | head -c 12
}

read -p "Digite usuário para o tomcat: " tomcatuser
read -p "Digite a senha: " tomcatpassword

# Verifica se o usuário inseriu um valor para usuário
if [ -z "$tomcatuser" ]; then
    # Se estiver em branco, gera um valor aleatório para usuário
    tomcatuser=$(generate_random_password)
fi

# Verifica se o usuário inseriu um valor para senha
if [ -z "$tomcatpassword" ]; then
    # Se estiver em branco, gera um valor aleatório para senha
    tomcatpassword=$(generate_random_password)
fi

#criar usuario sem permissao de login
sudo useradd -m -U -d /etc/tomcat -s /bin/false tomcat

#adiciona o tomcat ao grupo elotech
sudo usermod -aG elotech tomcat

#download tomcat
wget --no-check-certificate https://${mirror}/unix/release/tomcat/apache-tomcat-${tomcat_v}.tar.gz -P /tmp

mkdir -p /etc/tomcat

tar xvzf /tmp/apache-tomcat-${tomcat_v}.tar.gz -C /etc/tomcat/

ln -s apache-tomcat-${tomcat_v} /etc/tomcat/default

sudo chown tomcat:tomcat /etc/tomcat -R

sudo sh -c 'chmod +x /etc/tomcat/default/bin/*.sh'

rm -rf "/etc/tomcat/default/webapps/manager/META-INF/context.xml"

cat << EOF | sudo tee -a /etc/tomcat/default/webapps/manager/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?><Context antiResourceLocking="false" privileged="true" ><Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/></Context>
EOF

rm -rf "/etc/tomcat/default/conf/tomcat-users.xml"

cat << EOF | sudo tee -a /etc/tomcat/default/conf/tomcat-users.xml
<?xml version="1.0" encoding="UTF-8"?><tomcat-users xmlns="http://tomcat.apache.org/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd" version="1.0"><user username="$tomcatuser" password="$tomcatpassword" roles="admin-gui,manager-gui"/></tomcat-users>
EOF

if [ -f /etc/tomcat/default/webapps/manager/WEB-INF/web.xml ]; then
    sed -i 's/<max-file-size>52428800<\/max-file-size>/<max-file-size>209715200<\/max-file-size>/g' /etc/tomcat/default/webapps/manager/WEB-INF/web.xml
    sed -i 's/<max-request-size>52428800<\/max-request-size>/<max-request-size>209715200<\/max-request-size>/g' /etc/tomcat/default/webapps/manager/WEB-INF/web.xml
fi

systemctl enable tomcat.service

fi

}

services_create()
{

if [ -f "/etc/init.d/elotech-api" ]; then
rm -rf /etc/init.d/elotech-*
  if [ ! -f "/tmp/elotech-services.zip" ]; then
     wget --no-check-certificate https://${mirror}/unix/scripts/elotech-services.zip -P /tmp
  fi
  yes | unzip /tmp/elotech-services.zip -d /usr/lib/systemd/system/
fi
   
if [ -f "/etc/init.d/tomcat" ]; then
rm -rf /etc/init.d/tomcat
  if [ ! -f "/tmp/elotech-services.zip" ]; then
     wget --no-check-certificate https://${mirror}/unix/scripts/elotech-services.zip -P /tmp
     yes | unzip /tmp/elotech-services.zip -d /usr/lib/systemd/system/
  fi
fi

if [ ! -f "/usr/lib/systemd/system/elotech-api.service" ]; then
  if [ ! -f "/tmp/elotech-services.zip" ]; then
     wget --no-check-certificate https://${mirror}/unix/scripts/elotech-services.zip -P /tmp
  fi
  yes | unzip /tmp/elotech-services.zip -d /usr/lib/systemd/system/
fi

systemctl daemon-reload

}

app_start(){

echo "INFORME APPS A SEREM INSTALADOS"
echo "(1) Oxy API"
echo "(2) Oxy Portal Transparência"
echo "(3) Oxy Único"
echo "(4) Oxy Portal Contribuinte"
echo "(5) Tomcat"
echo "(6) Oxy Protocolo"
echo "(7) Oxy Report-Server"
echo "(8) Install Services"
echo "(9) Install Java 11"
echo "(10) Install Java 17"

# faz um replace na variavel apps_install trocando virgula por espaco
read -p ">>>: " apps_install
apps_install=${apps_install//,/' ' }

for apps in ${apps_install}
do
    if [ ${apps} = 1 ]; then
       apps_dir_create
       install_java
       install_nginx
       config_elo_nginx
       apps_dir_create
       install_oxy_api
    fi

    if [ ${apps} = 2 ]; then
       apps_dir_create
       install_java
       install_java11
       install_nginx
       config_elo_nginx
       install_oxy_api
       install_oxy_portal_transp
       services_create
    fi

    if [ ${apps} = 3 ]; then
       apps_dir_create
       install_java
       install_nginx
       config_elo_nginx
       install_oxy_unico
       services_create
    fi

    if [ ${apps} = 4 ]; then
       apps_dir_create
       install_java
       install_nginx
       config_elo_nginx
       install_oxy_portal_contrib
       services_create
    fi

    if [ ${apps} = 5 ]; then
       apps_dir_create
       install_java
       install_tomcat
       services_create
    fi

    if [ ${apps} = 6 ]; then
       apps_dir_create
       install_java
       install_nginx
       config_elo_nginx
       install_oxy_protocolo
       services_create
    fi

    if [ ${apps} = 7 ]; then
       apps_dir_create
       install_java
       install_nginx
       config_elo_nginx
       install_oxy_report_server
       services_create
    fi

    if [ ${apps} = 8 ]; then
       services_create
    fi
    
    if [ ${apps} = 9 ]; then
       install_java11
    fi
	
    if [ ${apps} = 10 ]; then
       install_java17
    fi

done

}

install_essential_package
app_start

