Bug 28364: Make log4perl.conf belong to the instance user
[koha.git] / debian / scripts / koha-create
1 #!/bin/bash
2 #
3 # koha-create -- Create a new Koha instance.
4 # Copyright 2010  Catalyst IT, Ltd
5
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 # Read configuration variable file if it is present
20 [ -r /etc/default/koha-common ] && . /etc/default/koha-common
21
22 set -e
23
24 # include helper functions
25 if [ -f "/usr/share/koha/bin/koha-functions.sh" ]; then
26     . "/usr/share/koha/bin/koha-functions.sh"
27 else
28     echo "Error: /usr/share/koha/bin/koha-functions.sh not present." 1>&2
29     exit 1
30 fi
31
32 usage()
33 {
34     local scriptname=$0
35     cat <<EOF
36
37 Creates new Koha instances.
38
39 Usage:
40
41   $scriptname [DB usage mode] [options] instancename
42
43 DB usage mode:
44   --create-db               Create a new database on localhost. (default).
45   --request-db              Creates a instancename-db-request.txt file where
46                             you adjust your DB settings and re-run with --populate-db.
47   --populate-db             Finish the installation you started with --request-db after
48                             you adjusted the instancename-db-request.txt file.
49   --use-db                  Use this option if you already created and populated your DB.
50
51 Options:
52   --marcflavor flavor       Set the MARC flavor. Valid values are marc21 (default),
53                             normarc and unimarc.
54   --zebralang lang          Choose the primary language for Zebra indexing. Valid
55                             values are cs, el, en (default), es, fr, nb, ru and uk.
56   --elasticsearch-server s  Enforce the use of the specified Elasticsearch server(s)
57                             (default: localhost:9200).
58   --memcached-servers str   Set a comma-separated list of host:port memcached servers.
59   --memcached-prefix str    Set the desired prefix for the instance memcached namespace.
60   --enable-sru              Enable the Z39.50/SRU server in Zebra search engine
61                             (default: disabled).
62   --sru-port                Specify a TCP port number for Zebra's Z39.50/SRU server
63                             to listen on. (default: 7090).
64   --defaultsql some.sql     Specify a default SQL file to be loaded on the DB.
65   --configfile cfg_file     Specify an alternate config file for reading default values.
66   --passwdfile passwd       Specify an alternate passwd file.
67   --dbhost host             Enforce the use of the specified DB server
68   --database dbname         Enforce the use of the specified DB name (64 char limit)
69   --adminuser n             Explicit the admin user ID in the DB. Relevant in
70                             conjunction with --defaultsql and --populate-db.
71   --template-cache-dir      Set a user defined template_cache_dir. It defaults to
72                             /var/cache/koha/<instance>/templates
73   --timezone time/zone      Specify a timezone. e.g. America/Argentina
74   --upload-path dir         Set a user defined upload_path. It defaults to
75                             /var/lib/koha/<instance>/uploads
76   --tmp-path dir            Set a user defined tmp_path. It defaults to
77                             /var/lib/koha/<instance>/tmp
78   --letsencrypt             Set up a https-only site with letsencrypt certificates
79   --smtp-host host          SMTP host name
80   --smtp-port NN            SMTP port
81   --smtp-timeout NN         Connection timeout in seconds
82   --smtp-ssl-mode mode      SSL mode. Options are 'disabled' (default), 'ssl' and 'starttls'.
83   --smtp-user-name user     User name to be used on SMTP auth
84   --smtp-password  pass     Password to authenticate SMTP
85   --smtp-debug              Enable debug mode for SMTP
86
87   --mb-host host            RabbitMQ host name (default: localhost)
88   --mb-port NN              RabbitMQ port (default: 61613)
89   --mb-user user            RabbitMQ user (default: guest)
90   --mb-pass pass            RabbitMQ password (default: guest)
91   --mb-vhost vhost          RabbitMQ vhost (default: koha_<instance>)
92
93   --help,-h                 Show this help.
94
95 Note: the instance name cannot be longer that 11 chars.
96
97 EOF
98 }
99
100 # UPPER CASE VARIABLES - from configfile or default value
101 # lower case variables - generated within this script
102 generate_config_file() {
103     touch "$2"
104     chown "root:$username" "$2"
105     # Bug 28364: the z3950 responder needs other permissions
106     [ "$1" = "log4perl-site.conf.in" ] && chown "$username:$username" "$2"
107
108     chmod 0640 "$2"
109     sed -e "s/__KOHA_CONF_DIR__/\/etc\/koha\/sites\/$name/g" \
110         -e "s/__KOHASITE__/$name/g" \
111         -e "s/__OPACPORT__/$OPACPORT/g" \
112         -e "s/__INTRAPORT__/$INTRAPORT/g" \
113         -e "s/__OPACSERVER__/$opacdomain/g" \
114         -e "s/__INTRASERVER__/$intradomain/g" \
115         -e "s/__ZEBRA_PASS__/$zebrapwd/g" \
116         -e "s/__ZEBRA_MARC_FORMAT__/$ZEBRA_MARC_FORMAT/g" \
117         -e "s/__ZEBRA_LANGUAGE__/$ZEBRA_LANGUAGE/g" \
118         -e "s/__SRU_BIBLIOS_PORT__/$SRU_SERVER_PORT/g" \
119         -e "s/__START_SRU_PUBLICSERVER__/$START_SRU_PUBLICSERVER/g" \
120         -e "s/__END_SRU_PUBLICSERVER__/$END_SRU_PUBLICSERVER/g" \
121         -e "s/__API_SECRET__/$API_SECRET/g" \
122         -e "s/__DB_NAME__/$mysqldb/g" \
123         -e "s/__DB_HOST__/$mysqlhost/g" \
124         -e "s/__DB_USER__/$mysqluser/g" \
125         -e "s/__DB_PASS__/$mysqlpwd/g" \
126         -e "s/__ELASTICSEARCH_SERVER__/${ELASTICSEARCH_SERVER}/g" \
127         -e "s/__UNIXUSER__/$username/g" \
128         -e "s/__UNIXGROUP__/$username/g" \
129         -e "s#__TEMPLATE_CACHE_DIR__#$TEMPLATE_CACHE_DIR#g" \
130         -e "s#__TIMEZONE__#$TIMEZONE#g" \
131         -e "s#__BCRYPT_SETTINGS__#$BCRYPT_SETTINGS#g" \
132         -e "s#__UPLOAD_PATH__#$UPLOAD_PATH#g" \
133         -e "s#__TMP_PATH__#$TMP_PATH#g" \
134         -e "s/__LOG_DIR__/\/var\/log\/koha\/$name/g" \
135         -e "s/__PLUGINS_DIR__/\/var\/lib\/koha\/$name\/plugins/g" \
136         -e "s/__MEMCACHED_NAMESPACE__/$MEMCACHED_NAMESPACE/g" \
137         -e "s/__MEMCACHED_SERVERS__/$MEMCACHED_SERVERS/g" \
138         -e "s/__SMTP_HOST__/$SMTP_HOST/g" \
139         -e "s/__SMTP_PORT__/$SMTP_PORT/g" \
140         -e "s/__SMTP_TIMEOUT__/$SMTP_TIMEOUT/g" \
141         -e "s/__SMTP_SSL_MODE__/$SMTP_SSL_MODE/g" \
142         -e "s/__SMTP_USER_NAME__/$SMTP_USER_NAME/g" \
143         -e "s/__SMTP_PASSWORD__/$SMTP_PASSWORD/g" \
144         -e "s/__SMTP_DEBUG__/$SMTP_DEBUG/g" \
145         -e "s/__MESSAGE_BROKER_HOST__/$MESSAGE_BROKER_HOST/g" \
146         -e "s/__MESSAGE_BROKER_PORT__/$MESSAGE_BROKER_PORT/g" \
147         -e "s/__MESSAGE_BROKER_USER__/$MESSAGE_BROKER_USER/g" \
148         -e "s/__MESSAGE_BROKER_PASS__/$MESSAGE_BROKER_PASS/g" \
149         -e "s/__MESSAGE_BROKER_VHOST__/$MESSAGE_BROKER_VHOST/g" \
150         "/etc/koha/$1" > "$2"
151
152 }
153
154 getmysqlhost() {
155     if [ ! -f /etc/mysql/debian.cnf ]
156     then
157         echo localhost
158         return
159     fi
160     awk '
161         BEGIN { FS="=" }
162         $1 ~/\[/ { inclient=0 }
163         $1 ~/\[client\]/ { inclient=1; next }
164         inclient==1 && $1 ~/host/ { gsub(/ /, "", $2); print $2 }' \
165         /etc/mysql/koha-common.cnf
166 }
167
168 getinstancemysqlpassword() {
169     xmlstarlet sel -t -v 'yazgfs/config/pass' "/etc/koha/sites/$1/koha-conf.xml"
170 }
171
172 getinstancemysqluser() {
173     xmlstarlet sel -t -v 'yazgfs/config/user' "/etc/koha/sites/$1/koha-conf.xml"
174 }
175
176 getinstancemysqldatabase() {
177     xmlstarlet sel -t -v 'yazgfs/config/database' "/etc/koha/sites/$1/koha-conf.xml"
178 }
179
180 check_apache_config()
181 {
182
183     # Check that mpm_itk is installed and enabled
184     if ! /usr/sbin/apachectl -M | grep -q 'mpm_itk'; then
185         # Check Apache version
186         APACHE_DISABLE_MPM_MSG=""
187         if /usr/sbin/apache2ctl -v | grep -q "Server version: Apache/2.4"; then
188             # mpm_event or mpm_worker need to be disabled first. mpm_itk depends
189             # on mpm_prefork, which is enabled if needed. See
190             # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=734865
191             if /usr/sbin/apachectl -M | grep -q 'mpm_event'; then
192                 APACHE_DISABLE_MPM_MSG=" sudo a2dismod mpm_event ;"
193             elif /usr/sbin/apachectl -M | grep -q 'mpm_worker'; then
194                 APACHE_DISABLE_MPM_MSG=" sudo a2dismod mpm_worker ;"
195             # else mpm_prefork: a2enmod mpm_itk works
196             fi
197         # else Apache 2.2: a2enmod mpm_itk works
198         fi
199
200         cat 1>&2  <<EOM
201
202 Koha requires mpm_itk to be enabled within Apache in order to run.
203 Typically this can be enabled with:
204
205    $APACHE_DISABLE_MPM_MSG sudo a2enmod mpm_itk
206 EOM
207
208         die
209     fi
210
211     # Check that mod_rewrite is installed and enabled.
212     if ! /usr/sbin/apachectl -M | grep -q 'rewrite_module'; then
213         cat 1>&2  <<EOM
214
215 Koha requires mod_rewrite to be enabled within Apache in order to run.
216 Typically this can be enabled with:
217
218     sudo a2enmod rewrite
219 EOM
220         die
221     fi
222
223     # Check that the CGI module is installed and enabled
224     # (Apache 2.4 may not have it by default.)
225     if ! /usr/sbin/apachectl -M | grep -q 'cgi_module'; then
226         cat 1>&2 << EOM
227 Koha requires mod_cgi to be enabled within Apache in order to run.
228 Typically this can be enabled with:
229
230     sudo a2enmod cgi
231 EOM
232         die
233     fi
234
235     # Check that mod_ssl is installed and enabled.
236     if [ "$CLO_LETSENCRYPT" = "yes" ]; then
237         if ! /usr/sbin/apachectl -M | grep -q 'ssl_module'; then
238             cat 1>&2  <<EOM
239
240 Koha requires mod_ssl to be enabled within Apache in order to run with --letsencrypt.
241 Typically this can be enabled with:
242
243     sudo a2enmod ssl
244 EOM
245             die
246         fi
247     fi
248
249 }
250
251 set_memcached()
252 {
253     local instance="$1"
254
255     if [ "$CLO_MEMCACHED_SERVERS" != "" ]; then
256         MEMCACHED_SERVERS=$CLO_MEMCACHED_SERVERS
257     else
258         if [ "$MEMCACHED_SERVERS" = "" ]; then
259             MEMCACHED_SERVERS=$DEFAULT_MEMCACHED_SERVERS
260         # else: was set by the koha-sites.conf file
261         fi
262     fi
263
264     if [ "$CLO_MEMCACHED_PREFIX" != "" ]; then
265         MEMCACHED_NAMESPACE="$CLO_MEMCACHED_PREFIX$instance"
266     else
267         if [ "$MEMCACHED_PREFIX" != "" ]; then
268             MEMCACHED_NAMESPACE="$MEMCACHED_PREFIX$instance"
269         else
270             MEMCACHED_NAMESPACE="$DEFAULT_MEMCACHED_PREFIX$instance"
271         fi
272     fi
273
274 }
275
276 set_smtp()
277 {
278     if [ "$CLO_SMTP_HOST" != "" ]; then
279         SMTP_HOST=$CLO_SMTP_HOST
280     fi
281
282     if [ "$CLO_SMTP_PORT" != "" ]; then
283         SMTP_PORT=$CLO_SMTP_PORT
284     fi
285
286     if [ "$CLO_SMTP_TIMEOUT" != "" ]; then
287         SMTP_TIMEOUT=$CLO_SMTP_TIMEOUT
288     fi
289
290     if [ "$CLO_SMTP_SSL_MODE" != "" ]; then
291         SMTP_SSL_MODE=$CLO_SMTP_SSL_MODE
292     fi
293
294     if [ "$CLO_SMTP_USER_NAME" != "" ]; then
295         SMTP_USER_NAME=$CLO_SMTP_USER_NAME
296     fi
297
298     if [ "$CLO_SMTP_PASSWORD" != "" ]; then
299         SMTP_PASSWORD=$CLO_SMTP_PASSWORD
300     fi
301
302     if [ "$CLO_SMTP_DEBUG" != "" ]; then
303         SMTP_DEBUG=$CLO_SMTP_DEBUG
304     fi
305 }
306
307 set_message_broker()
308 {
309     local instance="$1"
310
311     if [ "$CLO_MESSAGE_BROKER_HOST" != "" ]; then
312         MESSAGE_BROKER_HOST=$CLO_MESSAGE_BROKER_HOST
313     fi
314
315     if [ "$CLO_MESSAGE_BROKER_PORT" != "" ]; then
316         MESSAGE_BROKER_PORT=$CLO_MESSAGE_BROKER_PORT
317     fi
318
319     if [ "$CLO_MESSAGE_BROKER_USER" != "" ]; then
320         MESSAGE_BROKER_USER=$CLO_MESSAGE_BROKER_USER
321     fi
322
323     if [ "$CLO_MESSAGE_BROKER_PASS" != "" ]; then
324         MESSAGE_BROKER_PASS=$CLO_MESSAGE_BROKER_PASS
325     fi
326
327     if [ "$CLO_MESSAGE_BROKER_VHOST" != "" ]; then
328         MESSAGE_BROKER_VHOST=$CLO_MESSAGE_BROKER_VHOST
329     fi
330 }
331
332 set_upload_path()
333 {
334     local instance="$1"
335
336     if [ "$CLO_UPLOAD_PATH" != "" ]; then
337         UPLOAD_PATH=$CLO_UPLOAD_PATH
338     else
339         UPLOAD_PATH="$INSTANCE_PATH_BASE/$instance/$UPLOAD_DIR"
340     fi
341 }
342
343 set_tmp_path()
344 {
345     local instance="$1"
346
347     if [ "$CLO_TMP_PATH" != "" ]; then
348         TMP_PATH=$CLO_TMP_PATH
349     else
350         TMP_PATH="$INSTANCE_PATH_BASE/$instance/$TMP_DIR"
351     fi
352 }
353
354 enable_sru_server()
355 {
356     # remove the commenting symbols
357     START_SRU_PUBLICSERVER=""
358     END_SRU_PUBLICSERVER=""
359     if [ "$SRU_SERVER_PORT" = "" ]; then
360         # --sru-port not passed, use the default
361         SRU_SERVER_PORT=$DEFAULT_SRU_SERVER_PORT
362     fi
363 }
364
365 check_letsencrypt()
366 {
367     if [ $(dpkg-query -W -f='${Status}' letsencrypt 2>/dev/null | grep -c "ok installed") -eq 0 ]; then
368         set +e
369         apt-cache show letsencrypt &>/dev/null
370         local aptcacheshow=$?
371         set -e
372         if [ $aptcacheshow -eq 0 ]; then
373                 read -r -p "The letsencrypt package is not installed. Do it now?  [y/N] " response
374                 if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
375                     local debrelease="$(lsb_release -c -s)"
376                     if [ $debrelease = "jessie" ]; then
377                         apt-get install -y -t jessie-backports letsencrypt
378                     else
379                         apt-get install -y letsencrypt
380                     fi
381                 else
382                     die "You have to install letsencrypt to use the --letsencrypt parameter."
383                 fi
384         else
385             echo "No installation candidate available for package letsencrypt."
386             if [[ -f /usr/bin/letsencrypt ]]; then
387                 read -r -p "If you have a symlink from /usr/bin/letsencrypt to letsencrypt-auto, it should work. [y/N] " response
388                 if [[ ! $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
389                     die "You have to install letsencrypt to use the --letsencrypt parameter."
390                 fi
391             else
392                 die "You can create a symlink from /usr/bin/letsencrypt to letsencrypt-auto."
393             fi
394         fi
395     fi
396 }
397
398 letsencrypt_instance()
399 {
400     # Get letsencrypt certificates
401     letsencrypt --agree-tos --renew-by-default --webroot certonly \
402         -w /usr/share/koha/opac/htdocs/ -d $opacdomain -w /usr/share/koha/intranet/htdocs/ -d $intradomain
403     # enable all ssl settings (apache won't start with these before certs are present)
404     sed -i "s:^\s*#\(\s*SSL.*\)$:\1:" "/etc/apache2/sites-available/$name.conf"
405     # change port from 80 to 443. (apache won't start if it is 443 without certs present)
406     sed -i "s:^\s*\(<VirtualHost \*\:\)80> #https$:\1443>:" "/etc/apache2/sites-available/$name.conf"
407     # enable redirect from http to https on port 80
408     sed -i "s:^\s*#\(.*\)#nohttps$:\1:" "/etc/apache2/sites-available/$name.conf"
409     # make koha-list --letsencrypt aware of this instance # could be done by checking apache conf instead
410     echo -e "opacdomain=\"$opacdomain\"\nintradomain=\"$intradomain\"" > /var/lib/koha/$name/letsencrypt.enabled
411     # restart apache with working certs
412     service apache2 restart
413 }
414
415 # Set defaults and read config file, if it exists.
416 DOMAIN=""
417 OPACPORT="80"
418 OPACPREFIX=""
419 OPACSUFFIX=""
420 INTRAPORT="8080"
421 INTRAPREFIX=""
422 INTRASUFFIX=""
423 DEFAULTSQL=""
424 ZEBRA_MARC_FORMAT="marc21"
425 ZEBRA_LANGUAGE="en"
426 ADMINUSER="1"
427 PASSWDFILE="/etc/koha/passwd"
428
429 # SMTP config
430 SMTP_HOST="localhost"
431 SMTP_PORT="25"
432 SMTP_TIMEOUT="120"
433 SMTP_SSL_MODE="disabled"
434 SMTP_USER_NAME=""
435 SMTP_PASSWORD=""
436 SMTP_DEBUG="0"
437
438 # Message broker (a.k.a. RabbitMQ) config
439 DEFAULT_MESSAGE_BROKER_PREFIX="koha_"
440 MESSAGE_BROKER_HOST="localhost"
441 MESSAGE_BROKER_PORT="61613"
442 MESSAGE_BROKER_USER="guest"
443 MESSAGE_BROKER_PASS="guest"
444 MESSAGE_BROKER_VHOST=""
445
446 # memcached variables
447 USE_MEMCACHED="yes"
448 MEMCACHED_SERVERS=""
449 MEMCACHED_PREFIX=""
450 # elasticsearch config
451 ELASTICSEARCH_SERVER="localhost:9200"
452 # hardcoded memcached defaults
453 DEFAULT_MEMCACHED_SERVERS="127.0.0.1:11211"
454 DEFAULT_MEMCACHED_PREFIX="koha_"
455 # hardcoded instance base path
456 INSTANCE_PATH_BASE="/var/lib/koha"
457 UPLOAD_DIR="uploads"
458 UPLOAD_PATH=""
459 # timezone defaults to empty
460 TIMEZONE=""
461 # hardcoded upload_tmp_path
462 TMP_DIR="tmp"
463 TMP_PATH=""
464 # cache base dir
465 CACHE_DIR_BASE="/var/cache/koha"
466 # Generate a randomizaed API secret
467 API_SECRET="$(pwgen -s 64 1)"
468 # SRU server variables
469 ENABLE_SRU="no"
470 SRU_SERVER_PORT=""
471 # hardcoded default SRU server port
472 DEFAULT_SRU_SERVER_PORT="7090"
473 START_SRU_PUBLICSERVER="<!--"
474 END_SRU_PUBLICSERVER="-->"
475
476 APACHE_CONFIGFILE=""
477
478 if [ -e /etc/koha/koha-sites.conf ]
479 then
480     . /etc/koha/koha-sites.conf
481 fi
482
483 [ $# -ge 1 ] && [ $# -le 16 ] || ( usage ; die "Error: wrong parameters" )
484
485 TEMP=`getopt -o chrpm:l:d:f:b:a: -l create-db,request-db,populate-db,use-db,enable-sru,sru-port:,help,marcflavor:,auth-idx:,biblio-idx:,zebralang:,defaultsql:,configfile:,passwdfile:,dbhost:,database:,elasticsearch-server:,adminuser:,memcached-servers:,memcached-prefix:,template-cache-dir:,timezone:,upload-path:,tmp-path:,smtp-host:,smtp-port:,smtp-timeout:,smtp-ssl-mode:,smtp-user-name:,smtp-password:,smtp-debug,mb-host:,mb-port:,mb-user:,mb-pass:,mb-vhost:,letsencrypt, \
486      -n "$0" -- "$@"`
487
488 # Note the quotes around `$TEMP': they are essential!
489 eval set -- "$TEMP"
490
491 # Temporary variables for the command line options
492 CLO_ZEBRA_MARC_FORMAT=""
493 CLO_ZEBRA_LANGUAGE=""
494 CLO_DEFAULTSQL=""
495 CLO_ADMINUSER=""
496 CLO_MEMCACHED_SERVERS=""
497 CLO_MEMCACHED_PREFIX=""
498 CLO_ELASTICSEARCH_SERVER=""
499 CLO_UPLOAD_PATH=""
500 CLO_TMP_PATH=""
501 CLO_LETSENCRYPT=""
502 CLO_TEMPLATE_CACHE_DIR=""
503 CLO_TIMEZONE=""
504 CLO_SMTP_HOST=""
505 CLO_SMTP_PORT=""
506 CLO_SMTP_TIMEOUT=""
507 CLO_SMTP_SSL_MODE=""
508 CLO_SMTP_USER_NAME=""
509 CLO_SMTP_PASSWORD=""
510 CLO_SMTP_DEBUG=""
511
512 CLO_MESSAGE_BROKER_HOST=""
513 CLO_MESSAGE_BROKER_PORT=""
514 CLO_MESSAGE_BROKER_USER=""
515 CLO_MESSAGE_BROKER_PASS=""
516 CLO_MESSAGE_BROKER_VHOST=""
517
518 while true ; do
519     case "$1" in
520         -c|--create-db)
521             op=create ; shift ;;
522         -r|--request-db)
523             op=request ; shift ;;
524         -p|--populate-db)
525             op=populate ; shift ;;
526         -u|--use-db)
527             op=use ; shift ;;
528         --memcached-servers)
529             CLO_MEMCACHED_SERVERS="$2" ; shift 2 ;;
530         --memcached-prefix)
531             CLO_MEMCACHED_PREFIX="$2" ; shift 2;;
532         --elasticsearch-server)
533             CLO_ELASTICSEARCH_SERVER="$2" ; shift 2 ;;
534         -m|--marcflavor)
535             CLO_ZEBRA_MARC_FORMAT="$2" ; shift 2 ;;
536         -l|--zebralang)
537             CLO_ZEBRA_LANGUAGE="$2" ; shift 2 ;;
538         -d|--defaultsql)
539             CLO_DEFAULTSQL="$2" ; shift 2 ;;
540         -f|--configfile)
541             configfile="$2" ; shift 2 ;;
542         -s|--passwdfile)
543             CLO_PASSWDFILE="$2" ; shift 2 ;;
544         -b|--database)
545             CLO_DATABASE="$2" ; shift 2 ;;
546         --dbhost)
547             CLO_DBHOST="$2" ; shift 2 ;;
548         -a|--adminuser)
549             CLO_ADMINUSER="$2" ; shift 2 ;;
550         --enable-sru)
551             ENABLE_SRU="yes" ; shift ;;
552         --mb-host)
553             CLO_MESSAGE_BROKER_HOST="$2" ; shift 2 ;;
554         --mb-port)
555             CLO_MESSAGE_BROKER_PORT="$2" ; shift 2 ;;
556         --mb-user)
557             CLO_MESSAGE_BROKER_USER="$2" ; shift 2 ;;
558         --mb-pass)
559             CLO_MESSAGE_BROKER_PASS="$2" ; shift 2 ;;
560         --mb-vhost)
561             CLO_MESSAGE_BROKER_VHOST="$2" ; shift 2 ;;
562         --smtp-debug)
563             CLO_SMTP_DEBUG="1" ; shift ;;
564         --smtp-host)
565             CLO_SMTP_HOST="$2" ; shift 2 ;;
566         --smtp-port)
567             CLO_SMTP_PORT="$2" ; shift 2 ;;
568         --smtp-timeout)
569             CLO_SMTP_TIMEOUT="$2" ; shift 2 ;;
570         --smtp-ssl-mode)
571             CLO_SMTP_SSL_MODE="$2" ; shift 2 ;;
572         --smtp-user-name)
573             CLO_SMTP_USER_NAME="$2" ; shift 2 ;;
574         --smtp-password)
575             CLO_SMTP_PASSWORD="$2" ; shift 2 ;;
576         --sru-port)
577             SRU_SERVER_PORT="$2" ; shift 2 ;;
578         --template-cache-dir)
579             CLO_TEMPLATE_CACHE_DIR="$2" ; shift 2 ;;
580         --timezone)
581             CLO_TIMEZONE="$2" ; shift 2 ;;
582         --upload-path)
583             CLO_UPLOAD_PATH="$2" ; shift 2 ;;
584         --tmp-path)
585             CLO_TMP_PATH="$2" ; shift 2 ;;
586         --letsencrypt)
587             CLO_LETSENCRYPT="yes" ; shift ;;
588         -h|--help)
589             usage ; exit 0 ;;
590         --)
591             shift ; break ;;
592         *)
593             die "Internal error processing command line arguments" ;;
594     esac
595 done
596
597 # Load the configfile given on the command line
598 if [ "$configfile" != "" ]
599 then
600     if [ -e "$configfile" ]
601     then
602         . "$configfile"
603     else
604         die "$configfile does not exist.";
605     fi
606 fi
607
608 # Make sure options from the command line get the highest precedence
609 if [ "$CLO_ZEBRA_MARC_FORMAT" != "" ]
610 then
611     ZEBRA_MARC_FORMAT="$CLO_ZEBRA_MARC_FORMAT"
612 fi
613 if [ "$CLO_ZEBRA_LANGUAGE" != "" ]
614 then
615     ZEBRA_LANGUAGE="$CLO_ZEBRA_LANGUAGE"
616 fi
617 if [ "$CLO_DEFAULTSQL" != "" ]
618 then
619     DEFAULTSQL="$CLO_DEFAULTSQL"
620 fi
621 if [ "$CLO_ADMINUSER" != "" ]
622 then
623     ADMINUSER="$CLO_ADMINUSER"
624 fi
625 if [ "$CLO_PASSWDFILE" != "" ]
626 then
627     PASSWDFILE="$CLO_PASSWDFILE"
628 fi
629
630 if [ "$CLO_TIMEZONE" != "" ]; then
631     TIMEZONE=$CLO_TIMEZONE
632 fi
633
634 if [ "${CLO_ELASTICSEARCH_SERVER}" != "" ]; then
635     ELASTICSEARCH_SERVER="${CLO_ELASTICSEARCH_SERVER}"
636 fi
637
638 BCRYPT_SETTINGS=$(htpasswd -bnBC 10 "" password | tr -d ':\n' | sed 's/$2y/$2a/');
639
640
641 if [ "$ENABLE_SRU" != "no" ]; then
642     enable_sru_server
643 fi
644
645 [ $# -ge 1 ] || ( usage ; die "Missing instance name..." )
646
647 name="$1"
648
649 set_smtp
650 set_upload_path $name
651 set_tmp_path $name
652
653 if [ "$op" = use ] && [ "$CLO_DATABASE" = "" ] &&
654    ( [ ! -f "$PASSWDFILE" ] || [ ! `cat $PASSWDFILE | grep "^$name:"` ] )
655 then
656     cat <<NO_DB
657 --use-db must have a database name. It can be specified in a readable
658 password file ($PASSWDFILE). Using --passwdfile overrides the default
659 /usr/koha/passwd file. Each line of a passwd file should be in the format of:
660     instance:username:password:dbname:dbhost
661 A database name can also be specified using '--database dbname'.
662 NO_DB
663     die;
664 fi
665
666 if [ "$USE_MEMCACHED" = "no" ]; then
667     MEMCACHED_SERVERS=""
668     MEMCACHED_NAMESPACE=""
669     MEMCACHED_PREFIX=""
670 else
671     set_memcached $name
672 fi
673
674 set_message_broker $name
675
676 # Set template cache dir
677 if [ "$CLO_TEMPLATE_CACHE_DIR" != "" ]; then
678     TEMPLATE_CACHE_DIR="$CLO_TEMPLATE_CACHE_DIR"
679 else
680     TEMPLATE_CACHE_DIR="$CACHE_DIR_BASE/$name/templates"
681 fi
682
683 # Are we root? If not, the mod_rewrite check will fail and be confusing, so
684 # we look into this first.
685 if [[ $UID -ne 0 ]]
686 then
687     die "This script must be run with root privileges."
688 fi
689
690 # Check everything is ok with Apache, die otherwise
691 check_apache_config
692
693 opacdomain="$OPACPREFIX$name$OPACSUFFIX$DOMAIN"
694 intradomain="$INTRAPREFIX$name$INTRASUFFIX$DOMAIN"
695
696 # Check everything is ok with letsencrypt, die otherwise
697 if [ "$CLO_LETSENCRYPT" = "yes" ]; then
698     check_letsencrypt
699 fi
700
701 if [ -f $PASSWDFILE ] && [ `cat $PASSWDFILE | grep "^$name:"` ]
702 then
703     passwdline=`cat $PASSWDFILE | grep "^$name:"`
704     mysqluser=`echo $passwdline | cut -d ":" -f 2`
705     mysqlpwd=`echo $passwdline | cut -d ":" -f 3`
706     mysqldb=`echo $passwdline | cut -d ":" -f 4`
707     mysqlhost=`echo $passwdline | cut -d ":" -f 5`
708 fi
709
710 # The order of precedence for MySQL database name is:
711 # default < passwd file < command line
712 if [ "$mysqldb" = "" ]
713 then
714     mysqldb="koha_$name"
715 fi
716
717 if [ "$CLO_DATABASE" != "" ]
718 then
719     mysqldb="$CLO_DATABASE"
720 fi
721
722 if [ "$mysqluser" = "" ]
723 then
724     mysqluser="koha_$name"
725 fi
726
727 if [ "$CLO_DBHOST" != "" ]
728 then
729     mysqlhost="$CLO_DBHOST"
730 fi
731
732 if [ "$mysqlhost" = "" ]
733 then
734     mysqlhost="$(getmysqlhost)"
735 fi
736
737 if [ "$op" = create ] || [ "$op" = request ] || [ "$op" = use ]
738 then
739     if [ "$mysqlpwd" = "" ]
740     then
741         mysqlpwd="$(pwgen -s 15 1)"
742         mysqlpwd="$mysqlpwd@"
743     fi
744 else
745     mysqlpwd="$(getinstancemysqlpassword $name)"
746 fi
747
748
749 if [ "$op" = create ] || [ "$op" = request ] || [ "$op" = use ]
750 then
751     # Create new user and group.
752     username="$name-koha"
753     if getent passwd "$username" > /dev/null
754     then
755         die "User $username already exists."
756     fi
757     if getent group "$username" > /dev/null
758     then
759         die "Group $username already exists."
760     fi
761     adduser --no-create-home --disabled-login \
762         --gecos "Koha instance $username" \
763         --home "/var/lib/koha/$name" \
764         --quiet "$username"
765
766     # Create the site-specific directories.
767     koha-create-dirs "$name"
768
769     # Generate Zebra database password.
770     zebrapwd="$(pwgen -s 16 1)"
771     # Future enhancement: make this configurable for when your db is on
772     # another server.
773     mysql_hostname="localhost"
774     # Set up MySQL database for this instance.
775     if [ "$op" = create ]
776     then
777         if [ ! -e /etc/mysql/debian.cnf ]; then
778             MYSQL_OPTIONS="-u root"
779             echo "WARNING: The koha-common.cnf file is a dead soft link!"
780         else
781             MYSQL_OPTIONS="--defaults-extra-file=/etc/mysql/koha-common.cnf"
782         fi
783         mysql $MYSQL_OPTIONS <<eof
784 CREATE DATABASE \`$mysqldb\`;
785 CREATE USER \`$mysqluser\`@'$mysql_hostname' IDENTIFIED BY '$mysqlpwd';
786 GRANT ALL PRIVILEGES ON \`$mysqldb\`.* TO \`$mysqluser\`@'$mysql_hostname';
787 FLUSH PRIVILEGES;
788 eof
789     fi #`
790
791     if [ "$CLO_LETSENCRYPT" = "yes" ]; then
792         APACHE_CONFIGFILE="apache-site-https.conf.in"
793     else
794         APACHE_CONFIGFILE="apache-site.conf.in"
795     fi
796     # Generate and install Apache site-available file and log dir.
797     generate_config_file $APACHE_CONFIGFILE \
798         "/etc/apache2/sites-available/$name.conf"
799     mkdir "/var/log/koha/$name"
800     chown "$username:$username" "/var/log/koha/$name"
801
802
803     # Generate and install main Koha config file.
804     generate_config_file koha-conf-site.xml.in \
805         "/etc/koha/sites/$name/koha-conf.xml"
806
807     # Generate and install the log4perl config file.
808     generate_config_file log4perl-site.conf.in \
809         "/etc/koha/sites/$name/log4perl.conf"
810
811     # Generate and install Zebra config files.
812     generate_config_file zebra-biblios-dom-site.cfg.in \
813         "/etc/koha/sites/$name/zebra-biblios-dom.cfg"
814     generate_config_file zebra-authorities-dom-site.cfg.in \
815         "/etc/koha/sites/$name/zebra-authorities-dom.cfg"
816     generate_config_file zebra.passwd.in \
817         "/etc/koha/sites/$name/zebra.passwd"
818
819     # Create a GPG-encrypted file for requesting a DB to be set up.
820     if [ "$op" = request ]
821     then
822         touch "$name-db-request.txt"
823         chmod 0600 "$name-db-request.txt"
824         cat > "$name-db-request.txt" << eof
825 Please create a MySQL database and user on $mysqlhost as follows:
826
827 database name: $mysqldb
828 database user: $mysqluser
829      password: $mysqlpwd
830
831 Thank you.
832 eof
833
834         echo "See $name-db-request.txt for database creation request."
835         echo "Please forward it to the right person, and then run"
836         echo "$0 --populate-db $name"
837         echo "Thanks."
838     fi
839 fi
840
841
842 if [ "$op" = create ] || [ "$op" = populate ]
843 then
844     # Re-fetch the passwords from the config we've generated, allows it
845     # to be different from what we set, in case the user had to change
846     # something.
847     mysqluser=$(getinstancemysqluser $name)
848     mysqldb=$(getinstancemysqldatabase $name)
849     # Use the default database content if that exists.
850     if [ -e "$DEFAULTSQL" ]
851     then
852         # Populate the database with default content.
853         zcat -f "$DEFAULTSQL" |
854         sed "s/__KOHASITE__/koha_$name/g" |
855         mysql --host="$mysqlhost" --user="$mysqluser" --password="$mysqlpwd" "$mysqldb"
856
857
858         # Change the default user's password.
859         staffpass="$(pwgen 12 1)"
860         staffdigest=$(echo -n "$staffpass" |
861                       perl -e '
862                             use Digest::MD5 qw(md5_base64); 
863                             while (<>) { print md5_base64($_), "\n"; }')
864         mysql --host="$mysqlhost" --user="$mysqluser" \
865 --password="$mysqlpwd" <<eof
866 USE \`$mysqldb\`;
867 UPDATE borrowers 
868 SET password = '$staffdigest' 
869 WHERE borrowernumber = $ADMINUSER;
870 eof
871         #`
872         echo "staff user password is '$staffpass' but keep that secret"
873
874         # Upgrade the database schema, just in case the dump was from an 
875         # old version.
876         koha-upgrade-schema "$name"
877     else
878         echo "Koha instance is empty, no staff user created."
879     fi
880 fi
881
882
883 if [ "$op" = create ] || [ "$op" = populate ] || [ "$op" = use ]
884 then
885     # Reconfigure Apache.
886     if ! {
887         a2ensite "$name" > /dev/null 2>&1 ||
888             a2ensite "${name}.conf" > /dev/null 2>&1
889     }; then
890         echo "Warning: problem enabling $name in Apache" >&2
891     fi
892     service apache2 restart
893
894     # Start Zebra.
895     koha-zebra --start "$name"
896
897     # Start worker
898     koha-worker --start "$name"
899
900     if [ "$USE_INDEXER_DAEMON" = "yes" ]; then
901         # Start Indexer daemon
902         koha-indexer --start "$name"
903     fi
904
905     if [ "$CLO_LETSENCRYPT" = "yes" ]; then
906         # Get letsencrypt certificates
907         letsencrypt_instance
908     fi
909
910     chown $username:$username /var/log/koha/$name/*.log
911 fi
912
913
914 if [ "$op" = request ]
915 then
916     koha-disable "$name"
917 fi
918
919 echo <<eoh
920
921 Email for this instance is disabled. When you're ready to enable it, use:
922 koha-email-enable $name
923 eoh