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