Installation von OpenProject (Projektverwaltungsdienst) auf einem Uberspace-Nutzerkonto.

Aktuell ist es mir nicht möglich OpenProject mit Versionen von größer 4.0 zu installieren. Deshalb findet sich hier eine Anleitung nur dafür.

tl;dr

  • ./openproject-4.0-stable.sh
    • Standard-Installation; Falls eine Datenbank schon bestehen sollte, wird diese genutzt.
  • ./openproject-4.0-stable.sh installclean
    • Installation mit überschreiben einer evtl. bestehenden Datenbank.
  • ./openproject-4.0-stable.sh uninstall
    • Löschen vom OpenProject-Daemon und den OpenProject-Abhängigkeiten.
    • Bestehen bleiben die Datenbank und ein Backup des OpenProject-Git-Ordners.
  • ./openproject-4.0-stable.sh uninstalldb
    • Wie uninstall + entfernen der Datenbanken und des Git-Repositories.
  • ./openproject-4.0-stable.sh uninstallall
    • Löscht alle Inhalte, Datenbanken, Sources und Abhängigkeiten.
  • ./openproject-4.0-stable.sh uninstall && ./openproject-4.0-stable.sh
    • Upgrade auf die neuste stabile Version, sofern das in diesem Skript dargestellte Installationsmuster verwendet wurde.
wget frank.zisko.io/assets/code/2015/openproject-4.0-stable.sh
chmod u+x openproject-4.0-stable.sh
./openproject-4.0-stable.sh

Info

  • OpenProject ist eine Software für das Projektmanagement, welche als Web-Dienst aufgerufen wird (siehe auch Wikipedia).
    • Marketing-Sprech: web based collaboration
  • Vor der Installation sollte man sich das Sktipt natürlich durchlesen. Oder rechtlich für mich sicherer ausgedrückt:
    • Ich übernehme keine Gewähr für etwaige Fehler im Skript.
    • Die Nutzung des Skriptes geschieht auf eigene Gefahr.
  • Die Besonderheit dieses Skriptes ist es, dass die $HOME-Variable geändert wird.
    • Es gibt also ein anderes separates (Home-)Verzeichnis, in welches die Anwendung und die Installations-Dateien geschrieben werden.
    • Dadurch ist eine einfache, restlose Deinstallation möglich.
  • Vor dem Ausführen sollten drei Variablen geändert werden:
    • SUBDOMAIN=op
      • Aus dieser wird die Uberspace-Domain (sozusagen die immer zuerreichende Fallbackdomain) und die gewünschte eigene Sub-Domain zur Nutzung verfügbar gemacht.
      • Das schließt ein, dass du deine Domain bei Uberspace auch aufgeschaltet hast.
      • Zur Nutzung der HTTPS-Verbindung sollte auch ein eigenes Zertifikat beim Uberspace-Nutzerkonto hinterlegt sein. Ich verwende CAcert-Zertifikate.
    • DOMAINNAME="${SUBDOMAIN}.example.com"
      • Warum doppelt gemoppelt? Pustekuchen. Ist halt in diesem Skript so.
      • jedenfalls solltest du den example.com-Teil mit deiner Domain ersetzen.
      • Du hast keine eigene Domain? Egal, dann lass alles so. Der die Domain example.com ist eh nicht erreichbar, du klaust also niemanden etwas.
    • PORT=61000
      • Überspace erlaubt dir die Nutzung eigener Ports oberhalb 61000.
      • Du könntest dir einen freien Port reservieren. Dieser wäre dann auch aus dem Internet erreichbar. Brauchst du aber nicht.
      • Wähle eine Zahl zwischen 61000 und dem maximum von 65535.
      • Das Skript prüft selbst, ob dieser Port noch frei ist und bricht ab (bevor irgend etwas los geht), so dass du einen anderen Port auswählen kannst.
    • Solltest du parallel mehrere OpenProjekt-Installationen verwenden wollen, so ändere zusätzlich die Variable PROJECTNAME=openproject.
  • Direkt im Anschluss der Installation sollte man die im Domain subdomain.example.com aufrufen und sich einloggen.
    • Denn der Admin-Zugang ist standart-mäßig:
      • user: admin
      • password: admin
  • Beachte die Informationen, welche nach der Installation in der Konsole angezeigt werden.
  • Fragen oder Anregungen kannst du mir gern direkt stellen.

Data

Angelegte Dateien und Verzeichnisse:

  • /home/ubername/workspace/openproject-git
    • Git-Repository.
  • /home/ubername/workspace/openproject
    • Stable Checkout aus dem Git-Repo.
    • Arbeitsverzeichnis und Configurationsdatein.
  • /home/ubername/workspace/openproject-home
    • Darauf wird die $HOME-Variable geändert. Hier werden alle zur Installation und Laufzeit erstellten Dateien, welche normalerweise ins echte Homeverzeichnis geschrieben werden, abgelegt.
    • Beinhaltet auch eine .bashrc, um in die OpenProject-“Umgebung” zu wechseln.
  • /var/www/virtual/${USER}/${SUBDOMAIN}.${USER}.$(hostname -a).uberspace.de/
    • Immer erreichbare Domain für OpenProject.
    • Enthält eine .htaccess-Datei, welche erst auf eine https-Verbindung, dann auf den localhost und zum Schluss auf den OpenProject-Dienst umleitet.
  • /var/www/virtual/ubername/subdomain.example.com
    • Symbolischer Link auf /var/www/virtual/${USER}/${SUBDOMAIN}.${USER}.$(hostname -a).uberspace.de (/var/www/virtual/<uberuser>/<subdomain>.<uberuser>.<uberserver>.uberspace.de/)

Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
#!/usr/bin/env bash
################################################################################
################################################################################
# Author: Frank Zisko, 2015
# Version: 3.2.0.5
# Licence: MIT
#
# No warranty! For nothing. Use it at your own risk.
#
# See also: https://www.openproject.org/open-source/manual-installation/manual-installation-guide/
################################################################################
################################################################################


### Logging ### ################################################################
# Call this script again with logging parameters.
if [ -z "$IS_CALLED" ]; then
    export IS_CALLED=1
    # Get script path an set logging file.
    SCRIPT_PATH=$(cd `dirname "${BASH_SOURCE[0]}"` && pwd)/`basename "${BASH_SOURCE[0]}"`
    LOG_PATH=$(cd `dirname "${BASH_SOURCE[0]}"` && pwd)/`basename "${BASH_SOURCE[0]}"`.log
    . ${SCRIPT_PATH} ${1} 2>&1 | tee "${LOG_PATH}"
    # Exit here! If not, you'll go into endless recursive script calls!
    exit
    # Never reach this!
    echo "+++ If you read this line, abort this script immediately! +++"
    echo "+++ ABORT. THIS. SCRIPT. NOW! +++"
fi


### Log ### ####################################################################
JOB_NAME="Install OpenProject"
echo " "
echo "### Start Job: ${JOB_NAME} at $(date "+%Y-%m-%dT%H:%M:%S"). ###"
time_begin=$(date +"%s")


################################################################################
### Variables ### ##############################################################
################################################################################
# You just have to adjust these three variables:

    # Subdomain for this service.
    SUBDOMAIN=op
    # Domain. 
    # An Uberspace domain (<projectname>.<uberuser>.<uberserver>.uberspace.de) will be automatically added.
    DOMAINNAME="${SUBDOMAIN}.example.com"
    # Free usable port. Will be tested before the installation.
    PORT=65432

# UTF encoding.
LANG=en_US.UTF-8

# Project name. Used for installation and "virtual" home dir.
PROJECTNAME=openproject
# Place where all (other) projects are installed.
WORKSPACE=${HOME}/workspace

# The real home dir.
REALHOME=${HOME}
# Virtual home dir. It'll be usen for a clean installation and uninstallation.
VIRTHOME=${WORKSPACE}/${PROJECTNAME}-home
# This home dir.
HOME=${VIRTHOME}

# Versions.
OPENPROJECT_V="4.0"
RUBY_V="2.1.2"    # 2.0.0, 2.1.2, 2.2.2
RUBYVERSION="2.1" # 2.0,   2.1,   2.2
RUBYGEM_V="2.1.0" # 2.0.0, 2.1.0, 2.2.0
NODE_V="0.12.7"

# Paths:
# Home bin.
PATH=${HOME}/bin:${HOME}/.local/bin:${PATH}
# Ruby.
PATH=/package/host/localhost/ruby-${RUBY_V}/bin:${PATH}
PATH=${HOME}/.gem/ruby/${RUBYGEM_V}/bin:${PATH}
# Node.js.c
PATH=/package/host/localhost/nodejs-${NODE_V}/bin:${PATH}


################################################################################
### Uninstall ### ##############################################################
################################################################################
if [[ ("${1}" == "uninstall") || ("${1}" == "uninstallall") ]]; then
    echo "Uninstallation ..."
    HOME=${REALHOME}

  #### Services ####
    echo "  services ..."
    # OpenProject Web.
    SVC="${PROJECTNAME}-web"
    if [ -d "${HOME}/service/${SVC}" ]; then
        cd ${HOME}/service/${SVC}
        svc -dx . log
        rm ${HOME}/service/${SVC}
        
    fi
    if [ -d "${HOME}/etc/run-${SVC}" ]; then
        rm -rf ${HOME}/etc/run-${SVC}
    fi
    if [ -f "${HOME}/service/${SVC}" ]; then
        rm ${HOME}/service/${SVC}
    fi
    # OpenProject Worker.
    SVC="${PROJECTNAME}-worker"
    if [ -d "${HOME}/service/${SVC}" ]; then
        cd ${HOME}/service/${SVC}
        svc -dx . log
        rm ${HOME}/service/${SVC}
    fi
    if [ -d "${HOME}/etc/run-${SVC}" ]; then
        rm -rf ${HOME}/etc/run-${SVC}
    fi
    if [ -f "${HOME}/service/${SVC}" ]; then
        rm ${HOME}/service/${SVC}
    fi

  #### HTML links ####
    echo "  html links ..."
    if [ -n "${SUBDOMAIN}" ]; then
        cd /var/www/virtual/${USER}/
        rm -rf ${SUBDOMAIN}.${USER}.$(hostname -a).uberspace.de
    fi
    # Prevent deleting ${USER}s www directory, if ${DOMAINNAME} is empty.
    if [ -n "${DOMAINNAME}" ]; then
        cd /var/www/virtual/${USER}/
        rm -rf ${DOMAINNAME}
    fi

  #### Installation folder and all its content ####
    echo "  project dir and virtual home dir ..."
    # Virtual home directory.
    if [ -d "${WORKSPACE}/${PROJECTNAME}-home" ]; then
        rm -rf ${WORKSPACE}/${PROJECTNAME}-home
    fi
    # Project directory.
    if [ -d "${WORKSPACE}/${PROJECTNAME}" ]; then
        rm -rf ${WORKSPACE}/${PROJECTNAME}
    fi
    # Git directory.
    if [ "${1}" == "uninstallall" ]; then
        if [ -d "${WORKSPACE}/${PROJECTNAME}-git" ]; then
            rm -rf ${WORKSPACE}/${PROJECTNAME}-git
        fi
    fi

  #### Databases ####
    if [[ ("${1}" == "uninstallall") || ("${1}" == "uninstalldb") ]]; then
        echo "  database ..." 
        # Drop existing databases.
            # Check if database is existing.
            # Connect to database and instantly exiting database returns nothing.
            # No exisitng database returns an error.
        if [ -z "$(mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` --database="${USER}_${PROJECTNAME}" --execute=exit 2>&1 >/dev/null)" ]; then
            echo "    Drop existing database ${USER}_${PROJECTNAME}."
            mysql -e "DROP DATABASE ${USER}_${PROJECTNAME};"
        fi

        if [ -z "$(mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` --database="${USER}_${PROJECTNAME}_dev" --execute=exit 2>&1 >/dev/null)" ]; then
            echo "    Drop existing database ${USER}_${PROJECTNAME}_dev."
            mysql -e "DROP DATABASE ${USER}_${PROJECTNAME}_dev;"
        fi

        if [ -z "$(mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` --database="${USER}_${PROJECTNAME}_test" --execute=exit 2>&1 >/dev/null)" ]; then
            echo "    Drop existing database ${USER}_${PROJECTNAME}_test."
            mysql -e "DROP DATABASE ${USER}_${PROJECTNAME}_test;"
        fi
    fi

  #### End uninstallation ####
    echo "Uninstallation finished."
    exit 0
fi

################################################################################
### Check ### ##################################################################
################################################################################
echo "Checking existing installation ..."

#### Exist ####
# Check existing installation of openproject-web.
if [ -f ${HOME}/bin/${PROJECTNAME}-web ]; then
    echo "~/bin/${PROJECTNAME}-web exists."
    IS_INSTALLED=true
fi
# Check existing installation of openproject-worker.
if [ -f ${HOME}/bin/${PROJECTNAME}-worker ]; then
    echo "~/bin/${PROJECTNAME}-worker exists."
    IS_INSTALLED=true
fi
# Check termination condition.
if [ -n "${IS_INSTALLED}" ]; then
    echo "OpenProject files found. Maybe it is already installed. Aborting."
    exit 1
fi

echo "Checking server port, ruby and node ..."

#### Port ####
# Check if port is (already) unused.
if [ -z "$(netstat -tulpen | grep ${PORT})" ]; then
    echo "  Your choosen port (${PORT}) is available."
else
    echo "  Your choosen port (${PORT}) is not available. Choose another."
    echo "  Aborting the script."
    exit 2
fi

#### Ruby ####
# Check if ruby is available.
if [ -z "$(command -v ruby)" ]; then
    echo "  'ruby' command not found."
    RUBY_FOUND=false
else
    echo "  'ruby' command found."
    RUBY_FOUND=true
fi
# Check if gem is available.
if [ -z "$(command -v gem)" ]; then
    echo "  'gem' command not found."
    GEM_FOUND=false
else
    echo "  'gem' command found."
    GEM_FOUND=true
fi
# Check termination condition.
if [[ ! ( (${RUBY_FOUND} == true) && (${GEM_FOUND} == true) ) ]]; then
    echo "  Ruby is not complete. Aborting."
    exit 3
fi

#### Node ####
# Check if node is available.
if [ -z "$(command -v node)" ]; then
    echo "  'node' command not found."
    echo "  You may add 'export PATH=/package/host/localhost/nodejs-${NODE_V}/bin:\$PATH' into your ~/.bashrc file."
    NODE_FOUND=false
else
    echo "  'node' command found."
    NODE_FOUND=true
fi
# Check if npm is available.
if [ -z "$(command -v npm)" ]; then
    echo "  'npm' command not found."
    echo "  You may add 'export PATH=/package/host/localhost/nodejs-${NODE_V}/bin:\$PATH' into your ~/.bashrc file."
    NPM_FOUND=false
else
    echo "  'npm' command found."
    NPM_FOUND=true
fi
# Check termination condition.
if [[ ! ( (${NODE_FOUND} == true) && (${NPM_FOUND} == true) ) ]]; then
    echo "  Node is not complete. Aborting."
    exit 4
fi

################################################################################
### Setup environment ### ######################################################
################################################################################
echo "Setup build environment ..."

mkdir -p ${WORKSPACE}
mkdir -p ${WORKSPACE}/${PROJECTNAME}-home

# When you load this from your shell, you're in the installing environment.
cat > ${HOME}/.bashrc <<__EOF__
LANG=en_US.UTF-8

SUBDOMAIN=${SUBDOMAIN}
DOMAINNAME=${DOMAINNAME}
PORT=${PORT}
PROJECTNAME=${PROJECTNAME}
WORKSPACE=${WORKSPACE}

# The real home dir.
REALHOME=${REALHOME}
# Virtual home dir.
VIRTHOME=${VIRTHOME}
# This home dir.
HOME=${HOME}
alias getmyhomeback='HOME=${REALHOME}'

PATH=\${HOME}/bin:\${HOME}/.local/bin:\${PATH}
PATH=/package/host/localhost/ruby-${RUBY_V}/bin:\${PATH}
PATH=\${HOME}/.gem/ruby/${RUBYGEM_V}/bin:\${PATH}
PATH=/package/host/localhost/nodejs-${NODE_V}/bin:\${PATH}
__EOF__


################################################################################
### Download ### ###############################################################
################################################################################
echo "Cloneing OpenProject directory from repo ..."

if [ -d ${WORKSPACE}/${PROJECTNAME}-git ]; then
    cd ${WORKSPACE}/${PROJECTNAME}-git
    git pull > /dev/null 2>&1
    git checkout stable/${OPENPROJECT_V} > /dev/null 2>&1
else
    git clone https://github.com/opf/openproject.git ${WORKSPACE}/${PROJECTNAME}-git > /dev/null 2>&1
    cd ${WORKSPACE}/${PROJECTNAME}-git
    git checkout stable/${OPENPROJECT_V} > /dev/null 2>&1
fi

if [ -d ${WORKSPACE}/${PROJECTNAME} ]; then
    rm -rf ${WORKSPACE}/${PROJECTNAME}
    cp -r ${WORKSPACE}/${PROJECTNAME}-git ${WORKSPACE}/${PROJECTNAME}
    rm -rf ${WORKSPACE}/${PROJECTNAME}/.git
else
    cp -r ${WORKSPACE}/${PROJECTNAME}-git ${WORKSPACE}/${PROJECTNAME}
    rm -rf ${WORKSPACE}/${PROJECTNAME}/.git
fi


################################################################################
### Configure ### ##############################################################
################################################################################
echo "Configure OpenProject, its database and its gems ..."

#### configuration.yml ####
cat > ${WORKSPACE}/${PROJECTNAME}/config/configuration.yml <<__EOF__
production:
  email_delivery:
    delivery_method: :sendmail
    sendmail_settings:
      location: /usr/sbin/sendmail
      arguments: -i
rails_cache_store: :memcache
__EOF__

#### database.yml ####
cat > ${WORKSPACE}/${PROJECTNAME}/config/database.yml <<__EOF__
production:
  adapter: mysql2
  database: ${USER}_${PROJECTNAME}
  host: localhost
  username: ${USER}
  password: `my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'`
  encoding: utf8

development:
  adapter: mysql2
  database: ${USER}_${PROJECTNAME}_dev
  host: localhost
  username: ${USER}
  password: `my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'`
  encoding: utf8
__EOF__

#### Gemfile ####
cat > ${WORKSPACE}/${PROJECTNAME}/Gemfile.local <<__EOF__
gem 'rails_12factor'

# Gemfile.plugins
## PLUGINS:
## via https://www.openproject.org/download/install-plugins/openproject-plugins/
# To activate or deactivate uncomment or comment the 'gem "projectname", ...' and run:
# bundle install --quiet --path vendor/bundle --without postgres:sqlite:test
# RAILS_ENV=production bundle exec rake db:migrate


# Supported plugins: 

# Backlogs: Features for agile teams.
#gem "openproject-backlogs", :git => "https://github.com/finnlabs/openproject-backlogs.git", :branch => 'stable'

# PDF Export: Enables story card export for OpenProject Backlogs
#gem 'openproject-pdf_export', :git => 'https://github.com/finnlabs/openproject-pdf_export.git', :branch => 'stable'

# Meeting: Features to schedule, prepare, and hold meetings.
#gem 'openproject-meeting', :git => 'https://github.com/finnlabs/openproject-meeting.git', :branch => 'stable'

# Documents: Allows adding documents to projects.
#gem 'openproject-documents', :git => 'https://github.com/opf/openproject-documents.git', :branch => 'stable'

# Translations:  Adds user contributed languages to your OpenProject installation. All translations come from our crowdin project.
#gem 'openproject-translations', :git => 'https://github.com/opf/openproject-translations.git', :branch => 'stable'


# Sometimes buggy plugins:

# Global Roles: Allows users to create top-level projects
#gem 'openproject-global_roles', :git => 'https://github.com/finnlabs/openproject-global_roles.git', :branch => 'stable'

# Help Link: Allows to provide an alternative help link.
#gem 'openproject-help_link', :git => 'https://github.com/finnlabs/openproject-help_link.git', :branch => 'stable'

# My Project Page: Enables customization of a project’s overview page.
#gem 'openproject-my_project_page', :git => 'https://github.com/finnlabs/openproject-my_project_page.git', :branch => 'stable'

# Gives errors while login:
# Cost: Features for planning and tracking project costs.
#gem 'openproject-costs', :git => 'https://github.com/finnlabs/openproject-costs.git', :branch => 'stable'

# Reporting: Customized cost reporting features.
#gem 'reporting_engine', :git => 'https://github.com/finnlabs/reporting_engine.git', :branch => 'stable'

__EOF__


################################################################################
### Gems ### ###################################################################
################################################################################

mkdir -p ${HOME}/etc
echo "RUBYVERSION=${RUBYVERSION}" > ${HOME}/etc/rubyversion
echo "gem: --user-install --no-rdoc --no-ri" > ${HOME}/.gemrc

cd ${WORKSPACE}/${PROJECTNAME}

echo "Installing bundler via gem ..."
gem install --user bundler > /dev/null 2>&1

echo "Installing ruby dependencies (gems) via bundler ..."
bundle install --path vendor/bundle --without postgres sqlite test rmagick development therubyracer > /dev/null 2>&1


################################################################################
### Databases ### ##############################################################
################################################################################
echo "Set up the database ..."
cd ${WORKSPACE}/${PROJECTNAME}

if [ "${1}" == "installclean" ]; then
    echo "  delete old ones ..."
    # Drop existing databases.
        # Check if database is existing.
        # Connect to database and instantly exiting database returns nothing.
        # A non existing database returns an error.
    if [ -z "$(mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` --database="${USER}_${PROJECTNAME}" --execute=exit 2>&1 >/dev/null)" ]; then
        echo "Drop existing database ${USER}_${PROJECTNAME}."
        mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` -e "DROP DATABASE ${USER}_${PROJECTNAME}"
    fi

    if [ -z "$(mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` --database="${USER}_${PROJECTNAME}_dev" --execute=exit 2>&1 >/dev/null)" ]; then
        echo "Drop existing database ${USER}_${PROJECTNAME}_dev."
        mysql -e "DROP DATABASE ${USER}_${PROJECTNAME}_dev;"
    fi

    if [ -z "$(mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` --database="${USER}_${PROJECTNAME}_test" --execute=exit 2>&1 >/dev/null)" ]; then
        echo "Drop existing database ${USER}_${PROJECTNAME}_test."
        mysql -e "DROP DATABASE ${USER}_${PROJECTNAME}_test;"
    fi

    echo "  create new one ..."
    # Create new database.
    mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` -e "CREATE DATABASE ${USER}_${PROJECTNAME} CHARACTER SET utf8"
    #mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` -e "CREATE DATABASE ${USER}_${PROJECTNAME}_dev CHARACTER SET utf8"
    #mysql --user="${USER}" --password=`my_print_defaults --defaults-file=${REALHOME}/.my.cnf client | grep -- --password | awk -F = '{ print $2 }'` -e "CREATE DATABASE ${USER}_${PROJECTNAME}_test CHARACTER SET utf8"
fi

echo "  create, migrate and seed the database ..."
RAILS_ENV=production bundle exec rake db:create > /dev/null 2>&1
RAILS_ENV=production bundle exec rake generate_secret_token > /dev/null 2>&1
RAILS_ENV=production bundle exec rake db:migrate > /dev/null 2>&1
RAILS_ENV=production bundle exec rake db:seed > /dev/null 2>&1


################################################################################
### Node Package Manager & Bower ### ###########################################
################################################################################
cd ${WORKSPACE}/${PROJECTNAME}

# Node Package Manager.
cat > ${HOME}/.npmrc <<__EOF__
prefix = $HOME
umask = 077
__EOF__

# "Bower - A package manager for the web"
cat > ${HOME}/.bowerrc <<__EOF__
{
  "interactive": false
}
__EOF__
cat > ${WORKSPACE}/${PROJECTNAME}/.bowerrc <<__EOF__
{
  "directory": "vendor/assets/components"
}
__EOF__

# Help: https://docs.npmjs.com/cli/install
echo "Installing node modules via npm ..."
npm install > /dev/null 2>&1
echo "Installing bower via npm ..."
npm install -g bower > /dev/null 2>&1
echo "Installing bower components via bower ..."
bower install > /dev/null 2>&1


################################################################################
### Precompile OpenProject ### #################################################
################################################################################
echo "Precomile assets ..."
RAILS_ENV=production bundle exec rake assets:precompile > /dev/null 2>&1


################################################################################
### Startscripts ### ###########################################################
################################################################################
echo "Create OpenProject start scripts ..."

# OpenProject web starter.
mkdir -p ${HOME}/bin
cat > ${HOME}/bin/${PROJECTNAME}-web <<__EOF__
#!/usr/bin/env bash
HOME=${WORKSPACE}/${PROJECTNAME}-home
PATH=\${HOME}/bin:\${HOME}/.local/bin:\${PATH}
PATH=/package/host/localhost/ruby-${RUBY_V}/bin:\${PATH}
PATH=\${HOME}/.gem/ruby/${RUBYGEM_V}/bin:\${PATH}
PATH=/package/host/localhost/nodejs-${NODE_V}/bin:\${PATH}
# Start the application in the project folder.
cd ${WORKSPACE}/${PROJECTNAME}
exec bundle exec unicorn --port ${PORT} --env production
__EOF__
chmod +x ${HOME}/bin/${PROJECTNAME}-web

# OpenProject worker starter.
mkdir -p ${HOME}/bin
cat > ${HOME}/bin/${PROJECTNAME}-worker <<__EOF__
#!/usr/bin/env bash
HOME=${WORKSPACE}/${PROJECTNAME}-home
PATH=\${HOME}/bin:\${HOME}/.local/bin:\${PATH}
PATH=/package/host/localhost/ruby-${RUBY_V}/bin:\${PATH}
PATH=\${HOME}/.gem/ruby/${RUBYGEM_V}/bin:\${PATH}
PATH=/package/host/localhost/nodejs-${NODE_V}/bin:\${PATH}
# Use the production database.
export RAILS_ENV=production
# Start the application in the project folder.
cd ${WORKSPACE}/${PROJECTNAME}
exec bundle exec rake jobs:work
__EOF__
chmod +x ${HOME}/bin/${PROJECTNAME}-worker


################################################################################
### Start Services ### #########################################################
################################################################################
echo "Install OpenProject services ..."

# We change $HOME back to the real one.
# We need this for managing the project as service.
HOME=${REALHOME}
test -d ${HOME}/service || uberspace-setup-svscan
uberspace-setup-service ${PROJECTNAME}-web ${WORKSPACE}/${PROJECTNAME}-home/bin/${PROJECTNAME}-web &> /dev/null
uberspace-setup-service ${PROJECTNAME}-worker ${WORKSPACE}/${PROJECTNAME}-home/bin/${PROJECTNAME}-worker &> /dev/null


################################################################################
### Rewrite Proxy ### ##########################################################
################################################################################
echo "Install OpenProject apache rewrite proxy ..."

mkdir -p /var/www/virtual/${USER}/${SUBDOMAIN}.${USER}.$(hostname -a).uberspace.de
if [ -n "${DOMAINNAME}" ]; then
    ln -s /var/www/virtual/${USER}/${SUBDOMAIN}.${USER}.$(hostname -a).uberspace.de /var/www/virtual/${USER}/${DOMAINNAME}
fi

cat > /var/www/virtual/${USER}/${SUBDOMAIN}.${USER}.$(hostname -a).uberspace.de/.htaccess <<__EOF__
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{ENV:HTTPS} !=on
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

RewriteRule (.*) http://localhost:${PORT}/\$1 [P]
__EOF__


################################################################################
### Info ### ###################################################################
################################################################################
echo " "
echo "You can do your first login:"
echo "    https://${DOMAINNAME}"
echo "    user: admin"
echo "    password: admin"
echo "    Change the password immediately!"
echo " "
echo "To seed your OpenProject instance with roles, workflows, ...,"
echo "    got to: https://${DOMAINNAME}/settings?tab=display"
echo "    and set your language. "
echo "    After that, got to: https://${DOMAINNAME}/admin/projects"
echo "    select your language and click at 'loading default configuration'."
echo " "
echo "Restart OpenProject services:"
echo "    svc -du ~/service/${PROJECTNAME}-web"
echo "    svc -du ~/service/${PROJECTNAME}-worker"
echo "Logs will be written in:"
echo "    ~/service/${PROJECTNAME}-web/log/main/current"
echo "    ~/service/${PROJECTNAME}-worker/log/main/current"
echo " "
echo "For uninstallation call:"
echo "    $(cd `dirname "${BASH_SOURCE[0]}"` && pwd)/`basename "${BASH_SOURCE[0]}"` uninstall"
echo "For uninstallation including databases and git repo use:"
echo "    $(cd `dirname "${BASH_SOURCE[0]}"` && pwd)/`basename "${BASH_SOURCE[0]}"` uninstallall"


### Log ### ####################################################################
echo " "
time_end=$(date +"%s")
time_diff=$((${time_end}-${time_begin}))
echo "### Finished Job: ${JOB_NAME} at $(date "+%Y-%m-%dT%H:%M:%S"). ###"
echo "    $((${time_diff} / 60)) minutes and $((${time_diff} % 60)) seconds elapsed."
echo " "

################################################################################
################################################################################