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