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