install_PRODIGEV4.1.sh 36.9 KB
Newer Older
Sebastien QUESSON's avatar
Sebastien QUESSON committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
#!/bin/bash
#Installation complète Prodige 4.1
#29/05/2019
#https://gitlab.adullact.net/prodigeadmin/Prodige

#Definition du repertoire d'install source
SCRIPTDIR=`dirname $(readlink -f $0)`
SCRIPTNAME=`basename $(readlink -f $0)`
DATEINST=`date '+%y%m%d-%H%M'`
Netapes="10"
#adresse du depot debian stretch
SOURCES_LIST1="deb http://ftp.fr.debian.org/debian/ stretch main contrib non-free"
SOURCES_LIST2="deb http://security.debian.org/ stretch/updates  main contrib non-free"
SOURCES_LIST3="deb http://ftp.fr.debian.org/debian/ stretch-updates main"
SOURCES_LIST4="deb [arch=amd64] https://packagecloud.io/phalcon/stable/debian/ stretch main"

YEAR=`date '+%Y'`
DATE=`date '+%y%m%d'`
NUM="4.1.0"
VERSIONTXT="/home/sites/prodigecatalogue/web/version.txt"
PATCH_NAME="update_prodige${NUM}_29052019.tar.gz"
PATCH_TAG="prodige_${NUM}"
PATCH_DESC="Patch correctif prodige_${NUM}
- Installation de Prodige ${NUM}.
"
LDAP_DOMAIN="alkante.domprodige"
LDAP_ORGA="Prodige4"
OLDDNS_SUFFIX="-p40.alkante.com"
DB="CATALOGUE"
host_bdd="localhost"
user_tampon="user_tampon"
DB_tampon="tampon_tpl"


################################################
#options parsing
################################################

function usage(){
printf "Utilisation du script avec des options :\n"
printf "\t-n user_bdd\t : L'utilisateur de connexion postgres qui sera créé pour l'application, par exemple user_prodige\n" 
printf "\t-t THESAURUS_NAME : Le nom du thésaurus\n" 
printf "\t-u WWWURL\t : L'adresse d'accès au site principal\n" 
printf "\t-c SSLDIR\t : Le dossier des certificats SSL\n"
printf "\t-h\t\t : Affiche ce message.\n"
printf "Exemple : ./${SCRIPTNAME} -n user_prodige -t georegion -u www.georegion.fr -c /home/ssl\n"
printf "./${SCRIPTNAME} doit être lancé avec aucune option OU avec les 4 options\n"
}
error_exit()
{
echo "Annulation du script : $1" && exit 1
}
check()
{
case "$2" in
    var) [ -z $1 ] && error_exit "$3";;
    file) [ -f $1 ] || error_exit "Le fichier $1 n'existe pas";;
    dir) [ -d $1 ] || error_exit "Le répertoire $1 n'existe pas";;
esac
}


case $# in
    0) MODE=interactive;;
    8) MODE=noninteractive;;
    *) usage && exit 1;;
esac

OPTS=$( getopt -q -o n:,t:,u:,c: -- "$@" )
[ $? != 0 ] && usage && exit 1
eval set -- "$OPTS"

while true ; do
	case "$1" in
		-n) user_bdd="$2"
			shift 2;;
		-t) THESAURUS_NAME="$2"
			shift 2;;
		-u) WWWURL="$2"
			shift 2;;
		-c) SSLDIR="$2"
			shift 2;;
		--) shift; break;;
	esac
done

if [ $MODE == "noninteractive" ]; then
    for param in user_bdd THESAURUS_NAME WWWURL SSLDIR; do
        check "${!param}" "var" "Variable $param vide"
    done
fi



################################################
#Fonctions
################################################

ctl_saisie()
{
echo $1 | grep -Eq "$2" ; [ $? -eq 0 ] || error_exit "Format saisi \"$1\" : incorrect"
}

remove_trailing()
{
echo "$1"|sed "s/\(^.*\)\/$/\1/"
}

red='\033[31m';green='\033[32m';yellow='\033[33m';blue='\033[34m'
magenta='\033[35m';cyan='\033[36m';white='\033[37m'

color_echo()
{
message="$1";color="$2"
echo -en "$color";echo -e "$message"
tput sgr0
return
}  

echo_titre()
{
color_echo "\n\t${1}/$Netapes ${2}\n" "$cyan"
}

wait_exec()
{
rep="0"
[ "$rep" == "0" ]
while [ "$?" != "1" ] ; do
   echo -ne ". "
   sleep "$2"
   pgrep -f "$1" > /dev/null
done
echo
}

get_dom()
{
# WWWURL= www-domain.tld ou www.domain.tld ou www-xyz.domain.tld ou www.xyz.domain.tld
ctl_saisie "$WWWURL" "^www[\.-].*\..*$"
# DNS_SUFFIX= -domain.tld ou .domain.tld ou -xyz.domain.tld ou .xyz.domain.tld
DNS_SUFFIX=`echo "$WWWURL" | sed 's/^www//'`
# DOMAIN= domain.tld ou xyz.domain.tld
DOMAIN=`echo $DNS_SUFFIX | sed 's/^-\?[a-z0-9]*\.//'`
# DNS_PREFIX_SEP = . ou -
Chef Projet Prodige's avatar
Chef Projet Prodige committed
146
DNS_PREFIX_SEP=`echo $WWWURL | sed 's/\(www\|catalogue\)\([\.-]\).*$/\2/'`
Sebastien QUESSON's avatar
Sebastien QUESSON committed
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
}


change_mirror()
{
#Configurer les depôts Debian stretch
cp /etc/apt/sources.list /etc/apt/sources.list.bak.$DATEINST
echo "${SOURCES_LIST1}" > /etc/apt/sources.list
echo "${SOURCES_LIST2}" >> /etc/apt/sources.list
echo "${SOURCES_LIST3}" >> /etc/apt/sources.list
}

replace_postgres_conn()
{
echo -e "\tParamétrage de Postgres dans ${3}"
sed -i "
s|${1}|${user_bdd}|g
s|${2}|${pass_bdd}|g
" "${3}"
}

restart()
{
/etc/init.d/postgresql restart
/etc/init.d/apache2 restart
/etc/init.d/tomcat8 restart
/etc/init.d/jetty9 restart
}


################################################
#Verifications
################################################
verif()
{
echo
check "${SCRIPTDIR}" "dir"

#Verification version Debian
echo -ne "Version Debian Stretch "
if [ "`egrep "^9\." /etc/debian_version`" ] 
  then color_echo "OK" $green
  else color_echo "NOK, annulation de l'installation" $red;exit
fi

echo -ne "Architecture amd64 "
if [ "`dpkg --print-architecture |grep amd64`" ] 
  then color_echo "OK" $green
  else color_echo "NOK i386 détectée, annulation de l'installation" $red;exit
fi
echo

#Verification depot Debian
which wget > /dev/null 2>&1 || { color_echo "wget n'est pas installé, annulation de l'installation" $red;exit; }
SOURCES_LIST1_URL=`echo "${SOURCES_LIST1}" |awk '{ print $2 "dists/" $3 }'`
change_mirror
echo -ne "Vérification du dépôt Debian "
wget -O /dev/null -q "${SOURCES_LIST1_URL}"
if [ $? -eq 0 ]
 then color_echo "OK" $green
else color_echo "NOK
Veuillez mettre à jour manuellement l'adresse du dépôt dans la variable SOURCES_LIST1 de ce script
Puis relancez l'installation" $red;exit
fi
echo "Running apt update..."
apt-get -qq update
apt-get install -qqy openssl pwgen ca-certificates apt-transport-https

LDAP_PWD=`pwgen -s 10 1`
check "$LDAP_PWD" "var" "Le mot de passe LDAP n'a pu être généré"
SSL_PWD="$LDAP_PWD"
PHPCLI_DEFAULT_PWD=`pwgen -s 10 1`
check "$PHPCLI_DEFAULT_PWD" "var" "Le mot de passe PHPCLI_DEFAULT_PWD n'a pu être généré"
pass_bdd=`pwgen -s 10 1`
check "$pass_bdd" "var" "Le mot de passe postgres pour $user_bdd n'a pu être généré"

for dir in \
${SCRIPTDIR}/prodigeadmincarto \
${SCRIPTDIR}/prodigeadminsite \
${SCRIPTDIR}/prodigecatalogue \
${SCRIPTDIR}/prodigefrontcarto \
${SCRIPTDIR}/prodigetelecarto \
${SCRIPTDIR}/prodigedatacarto \
${SCRIPTDIR}/prodigegeosource \
${SCRIPTDIR}/cas \
${SCRIPTDIR}/cas-bundle \
${SCRIPTDIR}/prodige-bundle \
${SCRIPTDIR}/dist \
${SCRIPTDIR}/tasks \
;do check "$dir" "dir";done
for file in \
${SCRIPTDIR}/dist/editables_parameters.yml \
${SCRIPTDIR}/dist/dns_config_prod.yml \
${SCRIPTDIR}/cas/etc/cas/cas.properties \
${SCRIPTDIR}/cas/WEB-INF/classes/services/prodige4-proxy.json \
${SCRIPTDIR}/prodigegeosource/WEB-INF/config-overrides-prod.xml \
${SCRIPTDIR}/prodigegeosource/WEB-INF/config-db/jdbc.properties \
${SCRIPTDIR}/prodigegeosource/WEB-INF/config-security/config-security.properties \
${SCRIPTDIR}/prodigeadmincarto/carmenwsback/app/config/parameters.yml \
${SCRIPTDIR}/prodigegeosource/WEB-INF/classes/log4j.xml \
${SCRIPTDIR}/conf/geonetwork.xml \
${SCRIPTDIR}/conf/geonetwork_log4j.xml \
${SCRIPTDIR}/conf/start.ini \
${SCRIPTDIR}/conf/cas_log4j2.xml \
${SCRIPTDIR}/conf/server.xml \
${SCRIPTDIR}/conf/5_prodige_4.1.conf \
${SCRIPTDIR}/conf/alkante.ldif \
${SCRIPTDIR}/conf/import_init.ldif \
${SCRIPTDIR}/conf/p4.ldif \
${SCRIPTDIR}/conf/logrotate_prodige \
${SCRIPTDIR}/conf/0.conf \
${SCRIPTDIR}/files/ppolicy-conf.ldif \
${SCRIPTDIR}/files/ppolicy-default.ldif \
${SCRIPTDIR}/files/ppolicy-module.ldif \
${SCRIPTDIR}/bases/PRODIGE.sql \
${SCRIPTDIR}/bases/CATALOGUE.sql \
${SCRIPTDIR}/rights.sh \
${SCRIPTDIR}/uprod.sh \
;do check "$file" file ;done
}



################################################
#Variables utilisateur
################################################

start()
{
echo "Europe/Paris" > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata

echo -ne "Locales systême "
if [ "`egrep "^fr_FR ISO-8859-1" /etc/locale.gen`" ] && [ "`egrep "^fr_FR.UTF-8 UTF-8" /etc/locale.gen`" ] && [ `locale charmap` == "UTF-8" ]
    then color_echo "OK" $green
    else
         echo "Reconfiguration des paramétrages régionaux actifs"
         echo "Activation de FR utf8 et de FR latin1, avec utf8 par défaut"
         cp /etc/locale.gen /etc/locale.gen.$DATEINST
         echo "LANG=fr_FR.UTF-8" > /etc/default/locale 
         echo "fr_FR ISO-8859-1" > /etc/locale.gen
         echo "fr_FR.UTF-8 UTF-8" >> /etc/locale.gen
         locale-gen
         echo "La machine doit redémarrer, veuillez relancer l'install APRES REBOOT..."
         read -p "Appuyer sur Entrée pour redémarrer ou contrôle-C pour l'en empêcher"
         reboot &
	 exit 0
fi
}

ask()
{
if [ $MODE == "interactive" ]; then
    echo "Indiquer l'utilisateur de connexion postgres qui sera créé pour l'application, par exemple user_prodige ?"
    read user_bdd
    echo
    echo "Indiquer le nom du thésaurus ?"
    read THESAURUS_NAME
    echo
    echo "Indiquer l'url qui sera utilisée pour accéder au site prodige ?
Elle peut être sous une et une seule des formes suivantes:
- www.domaine.fr      => vous devez fournir un certificat SSL wildcard pour      *.domaine.fr
- www-test.domaine.fr => vous devez fournir un certificat SSL wildcard pour      *.domaine.fr
- www.test.domaine.fr => vous devez fournir un certificat SSL wildcard pour *.test.domaine.fr
Merci de saisir l'url en commençant par www. ou par www-
"
    read WWWURL
    echo
    get_dom
    echo "L'accès au site sera https://$WWWURL
Pour cela vous devez fournir un certificat wildcard pour *.$DOMAIN"
    echo "Indiquer le répertoire où se trouvent les fichiers du certificat SSL (wildcard.prodige4.crt, wildcard.prodige4.key et CA_intermediate.pem) ?"
    read SSLDIR
    echo
fi

check "$SSLDIR" "dir"
for cert in wildcard.prodige4.crt wildcard.prodige4.key CA_intermediate.pem; do
   check "$SSLDIR/$cert" "file"
done
echo
openssl verify -verbose -CAfile "$SSLDIR/CA_intermediate.pem"  "$SSLDIR/wildcard.prodige4.crt"
[ $? -eq 0 ] || error_exit "Erreur dans la vérification de la chaine des CA"
(openssl x509 -noout -modulus -in "$SSLDIR/wildcard.prodige4.crt"| openssl md5 ; openssl rsa -noout -modulus -in "$SSLDIR/wildcard.prodige4.key" | openssl md5) | uniq
[ $? -eq 0 ] || error_exit "Erreur $SSLDIR/wildcard.prodige4.crt ne correspond pas à $SSLDIR/wildcard.prodige4.key"
echo

get_dom

for param in user_bdd pass_bdd DB ; do
     check "${!param}" "var" "Variable $param vide"
done

echo "
Le script est prêt pour lancer l'installation avec les paramètres suivants:
- Le nom du thésaurus est : $THESAURUS_NAME
- L'accès au site sera https://$WWWURL avec un certificat wildcard pour *.$DOMAIN présent dans $SSLDIR
- Paramètres postgres: bases PRODIGE et $DB  / user=$user_bdd pass=$pass_bdd
- Mot de passe admin LDAP : $LDAP_PWD
- Mot de passe java SSL : $SSL_PWD
- Mot de passe cli admin : $PHPCLI_DEFAULT_PWD"
read -p "Pour démarrer l'installation, appuyez sur Entrée!"
echo
}



################################################
#Install paquets
################################################
install_utils()
{
sed -i "s/^127.0.0.1.*$/127.0.0.1 localhost www$DNS_SUFFIX catalogue$DNS_SUFFIX adminsite$DNS_SUFFIX telecarto$DNS_SUFFIX datacarto$DNS_SUFFIX admincarto$DNS_SUFFIX mapserv$DNS_SUFFIX carto$DNS_SUFFIX/" /etc/hosts
apt-get -qqy remove mailx exim4*
apt-get -qqy -o Dpkg::Options::='--force-confdef' -o Dpkg::Options::="--force-confold" install openssh-server ssh ftp unzip zip screen ntpdate time vim wget make autoconf libstdc++6 gcc cpp gnu-standards g++ sendmail sendmail-base sensible-mda sudo rsync bzip2 ed pwgen ca-certificates sharutils psmisc openssl python-numpy git  curl
#wkhtmltopdf 0.12.5.1 #phantomjs 2.1.1+dfsg-2
apt-get -qqy install xfonts-75dpi xfonts-base fontconfig libfontconfig phantomjs
cd /usr/local/src
wget -nv 'https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.5/wkhtmltox_0.12.5-1.stretch_amd64.deb' -O wkhtmltox_0.12.5-1.stretch_amd64.deb
dpkg -i wkhtmltox_0.12.5-1.stretch_amd64.deb
ln -s /usr/local/bin/wkhtmltopdf /usr/bin/wkhtmltopdf

which rsync > /dev/null 2>&1
[ $? -eq "0" ]  ||  error_exit "rsync n'est pas installé"
which pwgen > /dev/null 2>&1
[ $? -eq "0" ]  ||  error_exit "pwgen n'est pas installé"
pass_tampon=`pwgen -s 10 1`
check "$pass_tampon" "var" "pass_tampon n'a pu être généré"
}

install_apache()
{

curl -L "https://packagecloud.io/phalcon/stable/gpgkey" 2> /dev/null | apt-key add - &>/dev/null
echo "${SOURCES_LIST4}" > /etc/apt/sources.list.d/packagecloud_io_phalcon_stable_debian.list
echo "Running apt update..."
apt-get -qq update
apt-get -qqy install libapache2-mod-php7.0 php php-common php-http php-imagick php-memcache php-pear php-pecl-http php-propro php-raphf php7.0 php7.0-cli php7.0-common php7.0-curl php7.0-dev php7.0-gd php7.0-intl php7.0-json php7.0-ldap php7.0-mbstring php7.0-mcrypt php7.0-opcache php7.0-pgsql php7.0-readline php7.0-sqlite3 php7.0-xml php7.0-xsl php7.0-zip php7.0-ldap memcached apache2 file php7.0-phalcon php-yaml php-cas
}

conf_apache()
{
#Configuration de  php et d'Apache
cp /etc/php/7.0/apache2/php.ini /etc/php/7.0/apache2/php.ini.dist
#memory_limit
sed -i "s/^memory_limit = /;memory_limit = /g" /etc/php/7.0/apache2/php.ini
sed -i "/^;memory_limit = / i\memory_limit = 512M" /etc/php/7.0/apache2/php.ini
#post_max_size
sed -i "s/^post_max_size = /;post_max_size = /g" /etc/php/7.0/apache2/php.ini
sed -i "/^;post_max_size = / i\post_max_size = 500M" /etc/php/7.0/apache2/php.ini
#upload_max_filesize
sed -i "s/^upload_max_filesize = /;upload_max_filesize = /g" /etc/php/7.0/apache2/php.ini
sed -i "/^;upload_max_filesize = / i\upload_max_filesize = 500M" /etc/php/7.0/apache2/php.ini
#Reglage des sessions
sed -i "s/session.gc_maxlifetime = 1440/session.gc_maxlifetime = 3600/" /etc/php/7.0/apache2/php.ini
#maxclient 512
sed -i 's/MaxRequestWorkers[[:blank:]]*150/ServerLimit 512\n\tMaxRequestWorkers 512/' /etc/apache2/mods-available/mpm_prefork.conf

#secu
sed -i "s/^expose_php = On/;expose_php = On\nexpose_php = Off/" /etc/php/7.0/apache2/php.ini
sed -i "s/^ServerSignature.*$/ServerSignature Off/
s/^ServerTokens OS.*$/ServerTokens Prod/" /etc/apache2/conf-available/security.conf
echo 'umask 007' >> /etc/apache2/envvars
mkdir -p /etc/apache2/ssl-cert > /dev/null 2>&1
echo "Generating dhparam, please wait..."
openssl dhparam -dsaparam -out /etc/apache2/ssl-cert/dhparam.pem 4096 > /dev/null 2>&1
echo
sed -i "/SSLStrictSNIVHostCheck/ a\
SSLStaplingCache shmcb:/var/run/ocsp(128000)" /etc/apache2/mods-available/ssl.conf

#activation des modules et des sites
a2enmod proxy_http
a2enmod proxy
a2enmod rewrite
a2enmod ssl
a2enmod headers
a2enmod cgi
a2dissite 000-default.conf

apt-get -qqy install php-pecl-http

sed -i "/^APACHE_ULIMIT_MAX_FILES=/d
$ a\APACHE_ULIMIT_MAX_FILES='ulimit -n 65536'" /etc/apache2/envvars

#install composer
echo "Install composer"
echo "########################################################"
php $SCRIPTDIR/files/composer-setup.php --install-dir="/usr/local/bin"
ln -s /usr/local/bin/composer.phar /usr/local/bin/composer
which composer > /dev/null 2>&1
#[ $? -eq "0" ]  ||  error_exit "composer n'est pas installé"

echo "Gestion de la rotation des logs applicatifs apache / prodige"
echo "########################################################"
cp ${SCRIPTDIR}/conf/logrotate_prodige /etc/logrotate.d/prodige
chown root: /etc/logrotate.d/prodige
chmod 644 /etc/logrotate.d/prodige
logrotate -f /etc/logrotate.d/prodige > /dev/null 2>&1

echo
echo "Configuration des virtualhosts Apache"
echo "########################################################"
mkdir -p /etc/apache2/ssl-cert > /dev/null 2>&1
cp ${SCRIPTDIR}/conf/ssl.conf /etc/apache2/ssl-cert/
cp ${SCRIPTDIR}/conf/5_prodige*4.1.conf /etc/apache2/sites-available/
sed -i "s/#DOMAIN#/$DNS_SUFFIX/g" /etc/apache2/sites-available/5_prodige*4.1.conf
cd /etc/apache2/sites-available/
for conf in 5_prodige*4.1.conf; do a2ensite $conf; done
[ -f /etc/apache2/sites-available/0.conf ] && rm /etc/apache2/sites-available/0.conf
cp  ${SCRIPTDIR}/conf/0.conf /etc/apache2/sites-available/
sed -i "s/#DOMAIN#/$DNS_SUFFIX/g" /etc/apache2/sites-available/0.conf
[ -d /home/sites/nothing ] || mkdir -p /home/sites/nothing
a2ensite 0.conf
echo

echo "Installation des certificats SSL"
echo "########################################################"
#ssl global:
cp "$SSLDIR/CA_intermediate.pem" /usr/local/share/ca-certificates/CA_intermediate.crt
echo "Running update-ca-certificates..."
update-ca-certificates -v > /dev/null
echo

#ssl apache
cd /etc/apache2
[ -d ssl-cert ] || mkdir ssl-cert
cd ssl-cert
[ -d ssl.crt ] || mkdir ssl.crt
[ -d ssl.key ] || mkdir ssl.key
cp "$SSLDIR/wildcard.prodige4.crt" ssl.crt/wildcard.prodige4.crt.$YEAR
cd ssl.crt && ln -s wildcard.prodige4.crt.$YEAR wildcard.prodige4.crt
cd ..
cp "$SSLDIR/wildcard.prodige4.key" ssl.key/wildcard.prodige4.key.$YEAR
cd ssl.key && ln -s wildcard.prodige4.key.$YEAR wildcard.prodige4.key
cd ..
cp "$SSLDIR/CA_intermediate.pem" CA_intermediate.pem.$YEAR
ln -s CA_intermediate.pem.$YEAR CA_intermediate.pem
chmod 644 CA_intermediate.pem.$YEAR
}

install_tomcat()
{
apt-get -qqy install tomcat8
/etc/init.d/tomcat8 stop

sed -i 's/TOMCAT8_GROUP=tomcat8/TOMCAT8_GROUP=www-data/
s/TOMCAT8_USER=tomcat8/TOMCAT8_USER=www-data/
s/^JAVA_OPTS.*$/JAVA_OPTS=\"-Xms1024m -Xmx2048m -Xss2M -Xmn128M -XX:MaxPermSize=256m -XX:PermSize=256m -server -Djava.awt.headless=true -XX:+UseParallelGC -XX:+AggressiveOpts\"/' /etc/default/tomcat8
find -L /var/cache/tomcat8/ -user tomcat8 -exec chown www-data {} \;
find -L /var/lib/tomcat8/ -user tomcat8 -exec chown www-data {} \;
find -L /var/cache/tomcat8/ -group tomcat8 -exec chgrp www-data {} \;
find -L /var/lib/tomcat8/ -group tomcat8 -exec chgrp www-data {} \;
mkdir -p /usr/share/tomcat8/shared/classes
mkdir -p /usr/share/tomcat8/server/classes
sed -i '/^ulimit /d
2 a\ulimit -n 65536' /usr/share/tomcat8/bin/catalina.sh
echo

# ssl pour keystore tomcat
echo "Keystore for tomcat"
echo "########################################################"
mkdir /etc/tomcat8/ssl-cert
openssl pkcs12 -export -name wildcard.prodige4 -in "$SSLDIR/wildcard.prodige4.crt" -inkey "$SSLDIR/wildcard.prodige4.key" -out /etc/tomcat8/ssl-cert/wildcard.prodige4.p12.$YEAR -password pass:$SSL_PWD
keytool -importkeystore -destkeystore /etc/tomcat8/ssl-cert/prodige.keystore -srckeystore /etc/tomcat8/ssl-cert/wildcard.prodige4.p12.$YEAR -srcstoretype pkcs12 -srcalias wildcard.prodige4 -srcstorepass $SSL_PWD -deststorepass $SSL_PWD -noprompt
keytool -import -trustcacerts  -keystore /etc/ssl/certs/java/cacerts -storepass changeit -noprompt -file "$SSLDIR/CA_intermediate.pem" -alias wildcard.prodige4CA
echo

echo "Modification des rétentions de journaux tomcat8"
echo "########################################################"
cp $SCRIPTDIR/conf/logrotate_tomcat8 /etc/logrotate.d/tomcat8
chmod 600 /etc/logrotate.d/tomcat8
chown root: /etc/logrotate.d/tomcat8
echo

echo "Make tomcat starting after postgres"
mkdir -p /etc/systemd/system/tomcat8.service.d > /dev/null 2>&1
echo '[Unit]
After=postgresql@9.6-main.service' > /etc/systemd/system/tomcat8.service.d/order.conf
echo

echo "Changing file limits"
echo "########################################################"
sed -ir '/www-data (soft|hard) nofile/d' /etc/security/limits.conf
sed -i '$ i\www-data soft nofile 65536\nwww-data hard nofile 65536' /etc/security/limits.conf
sed -i '/^fs.file-max = .*$/d' /etc/sysctl.conf
echo 'fs.file-max = 65536' > /etc/sysctl.d/60-file-max.conf
sysctl --system
echo

echo "Install jetty"
echo "########################################################"
apt-get -qqy install jetty9
echo

echo "Configure jetty"
echo "########################################################"
cp /etc/default/jetty9 /etc/default/jetty9.bak
sed -i 's/NO_START=1/NO_START=0/
s/^.*LOGFILE_DAYS.$/LOGFILE_DAYS=7/
s/^.*JETTY_PORT.*$/JETTY_PORT=8380/
s/^.*JETTY_HOST.*$/JETTY_HOST=127.0.0.1/
s/^.*JETTY_USER.*$/JETTY_USER=www-data/' /etc/default/jetty9
cd /etc/jetty9 && mkdir ssl-cert > /dev/null 2>&1
cd ssl-cert
ln -sf /etc/tomcat8/ssl-cert/prodige.keystore

/etc/init.d/jetty9 stop
pkill -9 -f jetty9
rm /var/lib/jetty9/jetty.state
[ -f /var/run/jetty9.pid ] && rm /var/run/jetty9.pid
chown www-data: /var/lib/jetty9
mv /var/lib/jetty9/webapps /var/lib/jetty9/webapps.dist
mkdir /var/lib/jetty9/webapps
echo 
}


install_carto()
{
#install postgres
echo "Install postgres server"
echo "########################################################"
apt-get -qqy install  postgresql-9.6 postgresql-contrib postgis postgresql-9.6-postgis-scripts postgresql-9.6-postgis-2.3
echo

echo "Install carto"
echo "########################################################"
#Install paquets compiles par Alkante
#dep gdal
apt-get -qqy install curl libcurl3 libcurl3-gnutls libgeos-c1v5 libgif7 libjpeg62-turbo libpng16-16 python libsqlite3-0 libxerces-c3.1 libpq5 libxml2 libkmlbase1 libfreexl1 libexpat1 libopenjp2-7 libpcre3 libkmldom1 libkmlengine1 libkmlconvenience1
#dep mapserver
apt-get -qqy install libcairo2 libcurl3-gnutls libfcgi0ldbl libgd3 php7.0 proj-bin libproj12 libapache2-mod-fcgid
cd "${SCRIPTDIR}/deb"
dpkg -i libsvg_0.1.14-1stretch_amd64.deb libsvg-cairo_0.1.6-1stretch_amd64.deb
[ -f  /etc/apache2/mods-available/fcgid.conf ] && mv /etc/apache2/mods-available/fcgid.conf /etc/apache2/mods-available/fcgid.conf.bak
cp $SCRIPTDIR/conf/fcgid.conf /etc/apache2/mods-available/fcgid.conf
a2enmod fcgid
#dep mapcache
apt-get -qqy install curl libcurl3 libcurl3-gnutls libpng16-16 libjpeg62-turbo libtiff5 libpixman-1-0 libpcre3 libfcgi0ldbl

echo
cd "${SCRIPTDIR}/deb"
dpkg -i libecwj2_3.3-1stretch_amd64.deb
echo
dpkg -i gdal_2.2.3-1stretch_amd64.deb
echo
dpkg -i mapserv_7.0.7-1stretch_amd64.deb
mkdir /usr/lib/cgi-bin/ > /dev/null 2>&1
cp /usr/local/bin/mapserv /usr/lib/cgi-bin/mapserv
cp /usr/local/bin/mapserv /usr/lib/cgi-bin/mapservwfs
cp /usr/local/bin/mapserv /usr/lib/cgi-bin/mapserv.fcgi
chmod 755 /usr/lib/cgi-bin/mapserv*
echo "extension=php_mapscript.so" > /etc/php/7.0/mods-available/mapscript.ini
phpenmod mapscript
#php-ogr
echo
dpkg -i mapcache_1.4.2-1stretch_amd64.deb
ldconfig
echo 'LoadModule mapcache_module    /usr/lib/apache2/modules/mod_mapcache.so' > /etc/apache2/mods-available/mapcache.load
a2enmod mapcache
echo

#Epsg
echo "Install epsg"
cp -f $SCRIPTDIR/files/epsg /usr/share/proj/
ln -s /usr/lib/x86_64-linux-gnu/libproj.so.12 /usr/lib/x86_64-linux-gnu/libproj.so
ldconfig
}

install_ldap()
{
echo "Install LDAP"
echo "########################################################"
export DEBIAN_FRONTEND=noninteractive
sudo debconf-set-selections <<EOF
slapd slapd/internal/generated_adminpw password $LDAP_PWD
slapd slapd/password2 password $LDAP_PWD
slapd slapd/internal/adminpw password $LDAP_PWD
slapd slapd/password1 password $LDAP_PWD
slapd slapd/domain string $LDAP_DOMAIN
slapd shared/organization string $LDAP_ORGA
EOF
apt-get install -qqy slapd ldap-utils
echo

echo "Install LDAP data"
echo "########################################################"
echo -e "Import du schéma alkante.ldif"
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f ${SCRIPTDIR}/conf/alkante.ldif
sed -i 's|^SLAPD_SERVICES=.*$|SLAPD_SERVICES="ldap://127.0.0.1:389/ ldapi:///"|' /etc/default/slapd
/etc/init.d/slapd restart
echo
echo -e "Import de p4.ldif"
PHPCLI_DEFAULT_PWD_SSHA=`slappasswd -h {SSHA} -s "${PHPCLI_DEFAULT_PWD}" | sed 's|/|\\\/|g'`
sed -i "s/#PHPCLI_DEFAULT_PWD_SSHA#/${PHPCLI_DEFAULT_PWD_SSHA}/" ${SCRIPTDIR}/conf/p4.ldif
ldapadd -x -H ldap://localhost/ -D "cn=admin,dc=alkante,dc=domprodige" -w "$LDAP_PWD" -f ${SCRIPTDIR}/conf/p4.ldif 
echo
echo "Ajout des politiques des mots de passe"
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f /etc/ldap/schema/ppolicy.ldif
ldapmodify -Q -Y EXTERNAL -H ldapi:/// -f ${SCRIPTDIR}/files/ppolicy-module.ldif
ldapadd -Q -Y EXTERNAL -H ldapi:/// -f ${SCRIPTDIR}/files/ppolicy-conf.ldif
ldapadd -x -H ldap://localhost/ -D "cn=admin,dc=alkante,dc=domprodige" -w "$LDAP_PWD" -f ${SCRIPTDIR}/files/ppolicy-default.ldif
echo
}


copy_sources()
{
echo "Copie des données à partir de $SCRIPTDIR"
mkdir /home/sites > /dev/null 2>&1
check "/home/sites" "dir"
cd $SCRIPTDIR
for dir in prodigeadmincarto prodigeadminsite prodigecatalogue prodigefrontcarto prodigetelecarto prodigedatacarto cas cas-bundle prodige-bundle prodigegeosource
  do
    echo -e "\tInstallation de /home/sites/$dir ..."
    rsync -a $dir /home/sites/
  done
chmod -R 770 /home/sites
chown -R www-data: /home/sites
echo

cd $SCRIPTDIR/
echo "Copie de $SCRIPTDIR/prodige vers /home/"
cp -a prodige /home/
cd /home/sites/prodigefrontcarto/web/IHM
[ -d IHM ] || mkdir IHM
cd IHM
ln -s /home/prodige/cartes/IHM cartes
chmod -R 770 /home/prodige
chown -R www-data: /home/prodige
echo

find /home/prodige/cartes/ \( -name "*.map" -o -name "*.xml" \) -print0 |xargs -0 sed -i "s/${OLDDNS_SUFFIX}/${DNS_SUFFIX}/g"
find /home/prodige/cartes/ -type f -print0 |xargs -0 sed -i "s/F4QTrqxfWI/$pass_bdd/g"
find /home/prodige/cartes/ -type f -print0 |xargs -0 sed -i "s/user_p40/$user_bdd/g"
find /home/prodige/owscontext -type f -name "*.ows" -print0 |xargs -0 -r sed -i "s|$OLDDNS_SUFFIX|$DNS_SUFFIX|g"
find /home/prodige/cartes/Publication/ -type f -name "*.json" -print0 |xargs -0 -r sed -i "s|$OLDDNS_SUFFIX|$DNS_SUFFIX|g"
sed -i "s|alkante.com|$DOMAIN|" /home/prodige/SYSTEM/services.xml


echo "Edition des fichiers de configuration des sites"
echo "########################################################"

echo "prodigegeosource/WEB-INF/config-overrides.properties"
sed -i "
s/^overrides.ldap.security.credentials=.*$/overrides.ldap.security.credentials=${LDAP_PWD}/
s/^overrides.cas.baseURL=.*$/overrides.cas.baseURL=https:\/\/${WWWURL}\/cas/
s/^overrides.geonetwork.https.url=.*$/overrides.geonetwork.https.url=https:\/\/${WWWURL}\/geonetwork/
s/^overrides.jdbc.database=.*$/overrides.jdbc.database=${DB}/
s/^overrides.jdbc.username=.*$/overrides.jdbc.username=${user_bdd}/
s/^overrides.jdbc.password=.*$/overrides.jdbc.password=${pass_bdd}/
" /home/sites/prodigegeosource/WEB-INF/config-overrides.properties

echo "prodigegeosource/WEB-INF/config-db/jdbc.properties"
sed -i "
s/^jdbc.basic.maxWait.*$/jdbc.basic.maxWait=10000/
s/^jdbc.basic.maxActive.*$/jdbc.basic.maxActive=66/
s/^jdbc.host.*$/jdbc.host=${host_bdd}/
" /home/sites/prodigegeosource/WEB-INF/config-db/jdbc.properties

echo "prodigegeosource/WEB-INF/config-overrides-prod.xml"
sed -i "
s/\${prodige_domain}.*$/$DNS_SUFFIX<\/url>/
s/\${prodige_catalogue_prefix}/catalogue/
s/\${prodige_admincarto_prefix}/admincarto/
s/\${prodige_frontcarto_prefix}/carto/
s/\${prodige_telecarto_prefix}/telecarto/
" /home/sites/prodigegeosource/WEB-INF/config-overrides-prod.xml

cp ${SCRIPTDIR}/dist/favicon.ico /home/sites/
cp ${SCRIPTDIR}/dist/logo-client.png /home/sites/
sed '
> /cas_proxy_chain/ s/telecarto)-)/telecarto)/
> /cas_proxy_chain/ s/(www/www/' ${SCRIPTDIR}/dist/editables_parameters.yml >  /home/sites/editables_parameters.yml
sed '/\.DNS/ s/\.\"$/\"/
s/CAS.PORT.*$/CAS.PORT  : 443/' ${SCRIPTDIR}/dist/dns_config_prod.yml > /home/sites/dns_config.yml
cd /home/sites
for conffile in \
editables_parameters.yml \
dns_config.yml \
cas/etc/cas/cas.properties \
cas/WEB-INF/classes/services/prodige4-proxy.json \
prodigeadmincarto/carmenwsback/app/config/parameters.yml \
;do 
echo -e "$conffile"
sed -i "s/#DOMAIN#/$DNS_SUFFIX/g
s/#PRODIGE_VERSION#/4.1/
s/#DB_PRODIGE_NAME#/PRODIGE/g
s/#DB_PRODIGE_USER#/$user_bdd/g
s/#DB_PRODIGE_PWD#/$pass_bdd/g
s/#DB_CATALOGUE_NAME#/$DB/g
s/#DB_CATALOGUE_USER#/$user_bdd/g
s/#DB_CATALOGUE_PWD#/$pass_bdd/g
s/#DB_CATALOGUE_HOST#/$host_bdd/g
s/#PHPCLI_DEFAULT_LOGIN#/admincli/g
s/#PHPCLI_DEFAULT_PWD#/${PHPCLI_DEFAULT_PWD}/g
s/#LDAP_PWD#/$LDAP_PWD/g
s/#PATH_CACERT_PEM#/\/etc\/apache2\/ssl-cert\/CA_intermediate.pem/g" $conffile
done

sed -i "s/dns_url_prefix_sep.*$/dns_url_prefix_sep: \"$DNS_PREFIX_SEP\"/" /home/sites/prodigeadmincarto/carmenwsback/app/config/parameters.yml 
echo

echo "Composer"
echo "########################################################"
SITES="prodigeadmincarto/carmenwsback
prodigeadmincarto/carmenwsmapserv
prodigeadminsite
prodigecatalogue
prodigedatacarto
prodigefrontcarto
prodigetelecarto
prodige-bundle
cas-bundle
"
for SITE in $SITES
do
    if [ -d /home/sites/$SITE ] ; then
        echo -e "\tInstallation de composer pour $SITE" | tee -a ${SCRIPTDIR}/composer.log
        cd "/home/sites/$SITE" 
        composer self-update >> ${SCRIPTDIR}/composer.log 2>&1
        composer install >> ${SCRIPTDIR}/composer.log 2>&1
    fi
done
echo

echo "Installation des favicon.ico"
echo "########################################################"
for ico in \
/home/sites/prodigegeosource/images/logos/favicon.ico \
/home/sites/prodigeadmincarto/carmenwsback/web/favicon.ico \
/home/sites/prodigeadmincarto/carmenwsmapserv/web/favicon.ico \
/home/sites/prodigeadminsite/web/favicon.ico \
/home/sites/prodigecatalogue/web/favicon.ico \
/home/sites/prodigedatacarto/web/favicon.ico \
/home/sites/prodigefrontcarto/web/favicon.ico \
/home/sites/prodigetelecarto/web/favicon.ico \
;do
[ -f "${ico}" ] && rm "${ico}" && ln -sf /home/sites/favicon.ico "${ico}"
done
cp /home/sites/favicon.ico /home/sites/cas/favicon.ico
echo
echo "Installation des logos"
echo "########################################################"
for png in \
/home/sites/vendor/prodige/prodige/Prodige/ProdigeBundle/Resources/public/images/logo-client.png \
;do
[ -f "${png}" ] && rm "${png}" && ln -s /home/sites/logo-client.png "${png}"
done
cp /home/sites/logo-client.png /home/sites/cas/images/logo-client.png
echo


echo "Edition des fichiers de configuration tomcat"
echo "########################################################"
cp ${SCRIPTDIR}/conf/geonetwork_log4j.xml /home/sites/prodigegeosource/WEB-INF/classes/log4j.xml
cp ${SCRIPTDIR}/conf/geonetwork.xml /etc/tomcat8/Catalina/localhost/
chmod +r /etc/tomcat8/Catalina/localhost/*.xml
cp ${SCRIPTDIR}/conf/server.xml /etc/tomcat8/
sed -i "s/#SSL_PWD#/$SSL_PWD/g" /etc/tomcat8/server.xml
[ -d  /var/lib/tomcat8/webapps/ROOT ] && rm -rf /var/lib/tomcat8/webapps/ROOT
cp ${SCRIPTDIR}/conf/server.xml /etc/tomcat8/
sed -i "s/#SSL_PWD#/$SSL_PWD/g" /etc/tomcat8/server.xml
echo

echo "Edition des fichiers de configuration jetty"
echo "########################################################"
echo "Make jetty starting after slapd"
mkdir -p /etc/systemd/system/jetty9.service.d > /dev/null 2>&1
echo '[Unit]
After=slapd.service' > /etc/systemd/system/jetty9.service.d/order.conf
systemctl daemon-reload
echo
cp ${SCRIPTDIR}/conf/start.ini /etc/jetty9/start.d/
chmod 644 /etc/jetty9/start.d/start.ini
sed -i "s/#SSL_PWD#/$SSL_PWD/g" /etc/jetty9/start.d/start.ini
cp ${SCRIPTDIR}/conf/cas_log4j2.xml /home/sites/cas/WEB-INF/classes/log4j2.xml
chmod 750 /var/log/jetty9
chown www-data.adm /var/log/jetty9
cd /var/lib/jetty9/webapps
ln -s /home/sites/cas
echo
}

import_base()
{
echo
SOURCE="$SCRIPTDIR/bases/${1}.sql"
echo  "Re-création de la structure" | tee  -a "${2}" 
sudo -i -u postgres createdb -O "$user_bdd" ${3} "${1}" >> "${2}" 2>&1
sudo -i -u postgres psql -d "${1}" -c "CREATE EXTENSION postgis;"
echo -ne "Import de la base "  | tee  -a "${2}"
psql -U "${user_bdd}" -h $host_bdd -d "${1}" -f "${SOURCE}" >> "${2}" 2>&1 &
wait_exec "${SOURCE}" "2"
sudo -u postgres psql -d "${1}" -c "
grant all on geometry_columns to ${user_bdd};
grant all on spatial_ref_sys to ${user_bdd};
grant all on geography_columns to ${user_bdd};
" >> "${2}" 2>&1
}

install_base()
{
echo "$host_bdd:5432:PRODIGE:$user_bdd:$pass_bdd
$host_bdd:5432:$DB:$user_bdd:$pass_bdd
$host_bdd:5432:postgres:$user_bdd:$pass_bdd" >> /root/.pgpass
chmod 600 /root/.pgpass

echo "Paramétrage des scripts sql Postgres"
for i in www catalogue adminsite telecarto datacarto admincarto carto; do
   sed -i "s/${i}${OLDDNS_SUFFIX}/${i}${DNS_SUFFIX}/g" ${SCRIPTDIR}/bases/*.sql
done
sed -i "s/user_p40/$user_bdd/g
s/F4QTrqxfWI/$pass_bdd/g" ${SCRIPTDIR}/bases/*.sql

md5pass=`echo -n "${pass_bdd}${user_bdd}"|md5sum|awk '{ print $1 }'`
sudo -i -u postgres psql -c "CREATE ROLE ${user_bdd} ENCRYPTED PASSWORD 'md5${md5pass}' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;"
sudo -i -u postgres psql -c "CREATE ROLE user_admin ENCRYPTED PASSWORD 'md57cff8cc9d16b03d9dfcc7954b4662992' SUPERUSER CREATEDB CREATEROLE INHERIT LOGIN;"
su - postgres -c "psql -c \"ALTER ROLE $user_bdd SUPERUSER;\""

#Reglage de postgres pour la phase import
sed -i 's/#checkpoint_segments = 3/checkpoint_segments = 100/' /etc/postgresql/9.6/main/postgresql.conf
/etc/init.d/postgresql restart

LOG_CATALOGUE="$SCRIPTDIR/import_$DB.log"
import_base "${DB}" "$LOG_CATALOGUE" "--encoding=UTF8"
LOG_PRODIGE="$SCRIPTDIR/import_PRODIGE.log"
import_base "PRODIGE" "$LOG_PRODIGE" "--encoding=UTF8"

dns_tmp=`echo $DNS_SUFFIX | sed 's/^[\.-]//'`
su - postgres -c "psql -d PRODIGE -c \"set search_path to carmen; update lex_dns set dns_url = '$dns_tmp';\""

su - postgres -c "psql -c \"ALTER ROLE $user_bdd NOSUPERUSER NOCREATEDB NOCREATEROLE INHERIT LOGIN;\""
sed -i 's/checkpoint_segments = 100/#checkpoint_segments = 3/' /etc/postgresql/9.6/main/postgresql.conf
/etc/init.d/postgresql restart

echo "Ajout du tampon postgres"
echo "########################################################"
md5pass=`echo -n "${pass_tampon}${user_tampon}"|md5sum|awk '{ print $1 }'`
LOGtampon="${SCRIPTDIR}/tampon.log"
echo "Creating user ${user_tampon}..." | tee -a $LOGtampon
sudo -i -u postgres  psql -c "CREATE ROLE ${user_tampon} ENCRYPTED PASSWORD 'md5${md5pass}' NOSUPERUSER CREATEDB NOCREATEROLE INHERIT LOGIN;" >> $LOGtampon 2>&1
echo "Creating database $DB_tampon..." | tee -a $LOGtampon
sudo -i -u postgres createdb -T template0 --encoding='UTF-8' --lc-collate='fr_FR.UTF-8' --lc-ctype='fr_FR.UTF-8' -O "$user_tampon" "$DB_tampon" >> $LOGtampon 2>&1
sudo -i -u postgres createlang plpgsql "$DB_tampon" >> $LOGtampon 2>&1
sudo -i -u postgres psql -d "$DB_tampon" -c "CREATE EXTENSION postgis;" >> $LOGtampon 2>&1
sudo -i -u postgres psql -d "$DB_tampon" -c "grant all on geometry_columns to \"$user_tampon\";" >> $LOGtampon 2>&1
sudo -i -u postgres psql -d "$DB_tampon" -c "grant all on spatial_ref_sys to \"$user_tampon\";" >> $LOGtampon 2>&1
sudo -i -u postgres psql -d "$DB_tampon" -c "grant all on geography_columns to \"$user_tampon\";" >> $LOGtampon 2>&1
sed -i "
s/tampon_user:.*$/tampon_user: ${user_tampon}/
s/tampon_password:.*$/tampon_password: ${pass_tampon}/
" /home/sites/editables_parameters.yml
echo
rm /root/.pgpass
}

install_tasks()
{
echo "Installation des tâches planifiées"
echo "########################################################"
cd /etc/cron.d
echo '00 03           * * *   www-data    cd /home/sites/prodigeadminsite/ && /usr/bin/php app/console adminsite:generate_mapcache > /dev/null 2>&1' > p41_adminsite
echo '00 23           * * *   www-data    cd /home/sites/prodigeadmincarto/carmenwsback && /usr/bin/php app/console carmen:importdata > /dev/null 2>&1
30 23           * * *    www-data   cd /home/sites/prodigeadmincarto/carmenwsback && /usr/bin/php app/console carmen:cleanMaps > /dev/null 2>&1' > p41_admincarto
echo '00 00           * * *   www-data    cd /home/sites/prodigecatalogue/ && /usr/bin/php app/console prodige:password:lockexpired > /dev/null 2>&1
* *                * * *    www-data   cd /home/sites/prodigecatalogue/ && /usr/bin/php app/console scheduler:execute > /dev/null 2>&1' > p41_catalogue
echo '00,30 *         * * *   www-data    cd /home/sites/prodigeadminsite/ && /usr/bin/php app/console adminsite:populate_session_logs > /dev/null 2>&1' > p41_adminsite
echo '00 01         * * 6   www-data    cd /home/sites/prodigefrontcarto &&  /usr/bin/php app/console prodigefrontcarto:alertedition > /dev/null 2>&1' > p41_frontcarto
echo '10 01         * * 6   www-data    cd /home/sites/prodigefrontcarto &&  /usr/bin/php app/console prodigefrontcarto:sendmailingqueue > /dev/null 2>&1' > p41_frontcarto
echo '*/5 *           * * *   root        /home/tasks/queue_download.sh
30 00           * * *   root        /home/tasks/clean.sh' > p41
mkdir /home/tasks > /dev/null 2>&1
cp "${SCRIPTDIR}/tasks/"* /home/tasks/
chown root: /home/tasks/*.sh
chmod 700 /home/tasks/*.sh
echo

}



#mainjob:
echo "
#################################"
echo -e "Démarrage installation de Prodige 4.1"
echo "#################################"
echo

verif
start
ask

echo_titre "1" "INSTALL DES PAQUETS DEBIAN"
install_utils
echo_titre "2" "INSTALL APACHE-PHP"
install_apache
echo_titre "3" "CONFIG APACHE-PHP"
conf_apache
echo_titre "4" "INSTALL TOMCAT / JETTY"
install_tomcat
echo_titre "5" "INSTALL PAQUETS carto"
install_carto
echo_titre "6" "INSTALL CAS/LDAP"
install_ldap
echo_titre "7" "Installation des sources"
copy_sources
echo_titre "8" "Installation des bases de données"
install_base
echo_titre "9" "Redémarrage des services"
restart
echo_titre "10" "Inscription des tâches planifiées"
install_tasks
echo



cd /home/sites
echo "Génération du fichiers version.txt"
echo "########################################################"
echo "Génération du fichier version.txt"
echo -e "Patch ${PATCH_NAME} (${PATCH_TAG}) applied `date`\n${PATCH_DESC}\n-----------------------------------------------" > ./current_version.txt
[ -f "${VERSIONTXT}" ] || touch "${VERSIONTXT}"
ed -s  "${VERSIONTXT}" <<< $'0 r ./current_version.txt\n,w'
rm ./current_version.txt


uprod()
{
cp ${SCRIPTDIR}/uprod.sh /home/sites/
echo "Running symfony  php app/console, please wait ...."
echo "########################################################"
cd /home/sites
bash ./uprod.sh > ${SCRIPTDIR}/uprod.log 2>&1
echo "Ending symfony jobs"
echo
}

rights()
{
cp ${SCRIPTDIR}/rights.sh /home/
echo "Changing rights on filesystem, please wait ...."
echo "########################################################"
[ -f /home/rights.sh ] && [ -z "`ps ax | grep "/home/rights.sh" | grep -v grep`" ] && bash /home/rights.sh > /dev/null 2>&1
echo
}


uprod
rights
color_echo "L'installation est terminée" $yellow
echo
exit 0