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