aboutsummaryrefslogtreecommitdiff
path: root/scripts/rhodecode-setup
blob: a2065b1b362209f9aded25e4ce3a64402402e38d (plain)
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
#!/usr/bin/env python

# Copyright (C) 2013 Linaro Ltd.

import argparse
import datetime
import os
import subprocess
import sys


DESCRIPTION = "Install and setup RhodeCode Linaro instance."
REQUIRED_PACKAGES = ["python-pip", "python-webob", "python-bcrypt",
                     "python-mock", "python-babel", "python-dateutil",
                     "python-markdown", "python-webhelpers", "python-docutils",
                     "python-formencode", "python-pylons", "python-dev",
                     "python-pastescript", "python-psycopg2", "python-nose",
                     "build-essential", "python-amqplib", "python-anyjson",
                     "python-mailer", "apache2", "git"]
# Packages required for celery integration.
CELERY_REQUIRED_PACKAGES = ["rabbitmq-server"]

# Packages for the backend to use.
SQLITE_DB = "sqlite"
POSTGRESQL_DB = ["postgresql-9.1"]
# The name of the DB for PostgreSQL.
DB_NAME = "rhodecode"
DB_BACKUP_FILENAME = "rhodecode.backup.db"

# Packages to be installed via PIP.
PIP_PACKAGES = {}

# RhodeCode source to clone and which branch to use.
RHODECODE_SOURCE_GIT_URL = \
    "http://git.linaro.org/git-ro/infrastructure/rhodecode.git"
RHODECODE_SOURCE_BRANCH = "linaro"
RHODECODE_CO_DIR = "rhodecode"

# The name of the RhodeCode user to use by default. This will be used to
# install the RhodeCode code and to run RhodeCode.
RHODECODE_DEFAULT_USER = "rhodecode"

# Default RhodeCode directory for data and cache.
RHODECODE_DATA_DIR = "/opt/rhodecode"

# Default parameters for RabbitMQ setup.
RABBITMQ_DEFAULT_USER = "rhodecode"
RABBITMQ_DEFAULT_VHOST = "rhodecode-vhost"

# Default user for RhodeCode admin.
RHODECODE_ADMIN_USER = "admin"

# Upstart config files.
RHODECODE_UPSTART_CONF = "rhodecode-upstart.conf"
CELERY_UPSTART_CONF = "celeryd-upstart.conf"

# SQL string to create the new role in PostgreSQL.
POSTGRES_CREATE_ROLE = "CREATE ROLE %(role)s LOGIN CREATEDB PASSWORD '%(pwd)s'"

# The name of the PostgreSQL role to create.
POSTGRES_ROLE = "rhodecode"

# Default directory where to store git repositories.
REPOS_DIR = "/opt/rhodecode/git_repos"

# Default Celery log directory.
CELERY_LOG_DIR = "/var/log/celery"
# Default RhodeCode log directory.
RHODECODE_LOG_DIR = "/var/log/rhodecode"

# Default websites directory.
APACHE_DEFAULT_DIR = "/etc/apache2/sites-available/"
# Default modules to enalbe in Apache
APACHE_ENABLE_MODULES = ["proxy", "proxy_http"]
# Apache websites to disable.
APACHE_DISABLE_SITES = ["default"]


def cli_args():
    """Sets up the cli argument parser."""
    parser = argparse.ArgumentParser(description=DESCRIPTION)
    parser.add_argument("--rhodecode-config",
                        help="Path to the config INI file.",
                        required=True)
    parser.add_argument("--rhodecode-data-dir",
                        default=RHODECODE_DATA_DIR,
                        help="The directory where to store RhodeCode data "
                             "and cache. Defaults to '%s'." %
                             RHODECODE_DATA_DIR)
    parser.add_argument("--rhodecode-log-dir",
                        default=RHODECODE_LOG_DIR,
                        help="The directory to store RhodeCode logs. Defaults "
                             "to '%s'." % RHODECODE_LOG_DIR)
    parser.add_argument("--rhodecode-admin-usr",
                        default=RHODECODE_ADMIN_USER,
                        help="The name of the admin user for RhodeCode.")
    parser.add_argument("--rhodecode-admin-pwd",
                        help="The password for RhodeCode admin user.")
    parser.add_argument("--rhodecode-admin-email",
                        help="The email address for RhodeCode admin user.")
    parser.add_argument("--rhodecode-usr",
                        default=RHODECODE_DEFAULT_USER,
                        help="The name for the RhodeCode sytem user and "
                             "group.")
    parser.add_argument("--rhodecode-git-url",
                        default=RHODECODE_SOURCE_GIT_URL,
                        help="The URL where to clone RhodeCode source "
                             "code from.")
    parser.add_argument("--rhodecode-checkout-dir",
                        default=RHODECODE_CO_DIR,
                        help="The destination directory where to clone "
                             "RhodeCode code into. Defaults to '%s'." %
                             RHODECODE_CO_DIR)
    parser.add_argument("--rhodecode-branch",
                        default=RHODECODE_SOURCE_BRANCH,
                        help="The branch to use from the source code.")
    parser.add_argument("--assume-yes",
                        action="store_true",
                        help="Try to automate the process, assuming yes to "
                        "all questions.")
    parser.add_argument("--development",
                        action="store_true",
                        help="If the instance is a development instance.")
    parser.add_argument("--no-celery",
                        action="store_true",
                        help="If Celery integration should be disabled.")
    parser.add_argument("--celery-log-dir",
                        default=CELERY_LOG_DIR,
                        help="The Celery log directory. Defaults to '%s'." %
                             CELERY_LOG_DIR)
    parser.add_argument("--rabbitmq-usr",
                        default=RABBITMQ_DEFAULT_USER,
                        help="The name to use for the RabbitMQ session. "
                             "Defaults to '%s'." % RABBITMQ_DEFAULT_USER)
    parser.add_argument("--rabbitmq-pwd",
                        help="The password for the RabbitMQ user.")
    parser.add_argument("--rabbitmq-vhost",
                        default=RABBITMQ_DEFAULT_VHOST,
                        help="The name of the RabbitMQ vhost for the user. "
                             "Defaults to '%s'." % RABBITMQ_DEFAULT_VHOST)
    parser.add_argument("--dbname",
                        default=DB_NAME,
                        help="The name to use for the database. Defauls to "
                             "'%s'." % DB_NAME)
    parser.add_argument("--repos-dir",
                        default=REPOS_DIR,
                        help="Where the git repositories will be stored. "
                             "Defaults to '%s'." % REPOS_DIR)
    parser.add_argument("--postgres-role",
                        default=POSTGRES_ROLE,
                        help="The PostgreSQL role to create. Defaults "
                             "to '%s'." % POSTGRES_ROLE)
    parser.add_argument("--postgres-role-pwd",
                        help="The password for the PostgreSQL role.")
    parser.add_argument("--update",
                        action="store_true",
                        help="Updates to the latest tagged version.")
    parser.add_argument("--apache-conf",
                        help="Path to the Apache RhodeCode configuration.")
    parser.add_argument("--apache-website-dir",
                        default=APACHE_DEFAULT_DIR,
                        help="Path the the Apache sites directory. Defaults "
                             "to '%s'." % APACHE_DEFAULT_DIR)
    return parser.parse_args()


def check_cli_args(args):
    """Performs checks on the command line args passed.

    Logic to handle the various cases for the cli args.
    :param args: The args passed on the command line.
    """
    # Checks for required options during update.
    if not args.rhodecode_config:
        print ("It is necessary to specify the path to RhodeCode "
               "configuration file.")
        sys.exit(1)

    if args.update:
        if not args.rhodecode_usr:
            print ("During update it is necessary to specify the RhodeCode"
                   "system user.")
            sys.exit(1)
        if not args.rhodecode_branch:
            print ("During update it is necessary to specify the RhodeCode"
                   "repository tag to use (i.e. v1.5.1).")
            sys.exit(1)
        if not args.rhodecode_checkout_dir:
            print ("During update it is necessary to specify the RhodeCode"
                   "checkout directory.")
            sys.exit(1)
        if not args.dbname:
            print ("During update it is necessary to specify the RhodeCode"
                   "database name.")
            sys.exit(1)

    else:
        if not args.rhodecode_admin_pwd:
            print ("It is necessary to specify the administration "
                   "password for RhodeCode")
            sys.exit(1)
        if not args.rhodecode_admin_email:
            print ("It is necessary to specify the administration "
                   "email for RhodeCode")
            sys.exit(1)
        if not args.apache_conf:
            print ("It is necessary to specify the path to apache "
                   "configuration file")
            sys.exit(1)
        if not args.postgres_role_pwd:
            print ("It is necessary to specify the PostgreSQL "
                   "user password")
            sys.exit(1)
        if not args.rabbitmq_pwd:
            print ("It is necessary to specify the RabbitMQ "
                   "password")
            sys.exit(1)

        if not args.no_celery:
            if (args.rabbitmq_usr == RABBITMQ_DEFAULT_USER or \
                args.rabbitmq_vhost == RABBITMQ_DEFAULT_VHOST):
                print ("Warning: default values for --rabbitmq-user and/or "
                       "--rabbitmq-vhost are being used.")

            if not args.rabbitmq_pwd:
                print ("To setup RhodeCode to correctly use Celery, it is "
                       "necessary to specify also the RabbitMQ user password.")
                sys.exit(1)


def setup_user(user, home_dir, group):
    """Creates the necessary user and its associated group.

    :param user: The name of the user and group to create.
    """
    # Add the user group.
    cmd_args = ["addgroup", "--system", group]
    execute_command(cmd_args)

    # Add the user.
    cmd_args = ["adduser", "--system", "--home", home_dir, "--ingroup",
                group, user]
    execute_command(cmd_args)


def setup_directories(directories, rhodecode_usr):
    """Sets up the correct necessary directories."""
    if not isinstance(directories, list):
        directories = [directories]

    for directory in directories:
        if not os.path.exists(directory):
            cmd_args = ["mkdir", "-p", directory]
            execute_command(cmd_args)
        # Set ownership of the directories to the RhodeCode user.
        set_owners(directory, rhodecode_usr)


def execute_command(cmd_args,
                    work_dir=os.getcwd(),
                    with_sudo=True,
                    input_str=None,
                    continue_on_error=False):
    """Runs the command passed.

    :param cmd_args: List of command and options to run.
    :type list
    :param word_dir: Where the command must be run. Defaults to current dir.
    :type str
    :param with_sudo: If the command must be executed as root. Defaults to
    True.
    :type bool
    :param input_str: String to pass to the process as input, in order to
    automate as much as possible.
    :type str
    :param continue_on_error: If an error arise, continue instead of exiting.
    Default to False.
    :type bool
    """
    if not isinstance(cmd_args, list):
        cmd_args = list(cmd_args)
    if with_sudo:
        cmd_args.insert(0, "sudo")
    if input_str:
        process = subprocess.Popen(cmd_args,
                                   cwd=work_dir,
                                   stdin=subprocess.PIPE)
        process.communicate(input=input_str)

    else:
        process = subprocess.Popen(cmd_args,
                                   cwd=work_dir)
        process.communicate()

    if continue_on_error:
        return
    elif process.returncode != 0:
        print "Error executing the following command: %s" % " ".join(cmd_args)
        sys.exit(1)


def update_repositories():
    """Performs an 'apt-get update' on the system."""
    cmd_args = ["apt-get", "update"]
    execute_command(cmd_args)


def add_launchpad_ppa(ppa_string, assume_yes=False):
    """Adds a PPA repository from Launchpad.

    :param ppa_string: The PPA string as found in Launchpad.
    :type str
    """
    input_str = None
    cmd_args = ["apt-add-repository", ppa_string]
    if assume_yes:
        input_str = "\n"
    execute_command(cmd_args, input_str=input_str)


def install_packages(packages, assume_yes=False):
    """Installs a new package in the system.

    :param packages: The packages to install.
    :type list
    """
    input_str = None
    if not isinstance(packages, list):
        packages = [packages]
    cmd_args = ["apt-get", "install"] + packages
    if assume_yes:
        input_str = "Y"
    execute_command(cmd_args, input_str=input_str)


def install_pip_packages(packages, user=None):
    """Installs packages from PIP.

    :param packages: The packages to install. It has to be a dictionary, with
    key the name of the package, and value the version number or None.
    :type dict
    :param user: The user to install the PIP package as. This will append
    --user to the command line.
    :type str
    """
    for key, value in packages.iteritems():
        print "Installing package %s with PIP..." % key
        cmd_args = ["pip", "install", "-I"]
        if value:
            cmd_args.append("%s==%s" % (key, value))
        else:
            cmd_args.append(key)
        cmd_args.append("-U")
        if user:
            cmd_args = ["-u", user] + cmd_args
            cmd_args.append("--user")
        execute_command(cmd_args)


def install_git_from_ppa(assume_yes=False):
    """Install git from the git maintainers Launchpad PPA.

    :param assume_yes: If operation has to be automated.
    :type bool
    """
    print "Installing git-core package from git maintainers PPA..."
    install_packages("python-software-properties", assume_yes=assume_yes)
    add_launchpad_ppa("ppa:git-core/ppa", assume_yes=assume_yes)
    update_repositories()
    install_packages("git-core", assume_yes=assume_yes)


def create_postgresql_role(role, pwd, postgres_usr="postgres"):
    """Creates a new PostgreSQL role.

    :param role: The name of the role to create.
    :type str
    :param pwd: The password to set to the new role.
    :type str
    :param postgres_usr: The superuser for PostreSQL. Defaults to 'postgres'.
    :type str
    """
    postgres_commamd = POSTGRES_CREATE_ROLE % dict(role=str(role),
                                                   pwd=str(pwd))
    cmd_args = ["-u", postgres_usr, "psql", "-c", str(postgres_commamd)]
    execute_command(cmd_args)


def create_postgresql_db(db_name, role):
    """Creates the PostgreSQL database.

    :param db_name: The name of the database to create.
    :type str
    :param role: The name of the postregsql user.
    :type str
    """
    print "Creating PostgreSQL database..."
    cmd_args = ["-u", role, "createdb", db_name]
    execute_command(cmd_args)


def setup_rabbitmq_server(user, password, vhost):
    """Sets up RabbitMQ server.

    :param user: The name of the user for the RabbitMQ session.
    :type str
    :param password: The password for the RabbitMQ user.
    :type str
    :param vhost: The name of the RabbitMQ vhost to create.
    :type str
    """
    cmd_args = ["rabbitmqctl", "add_user", user, password]
    execute_command(cmd_args)

    cmd_args = ["rabbitmqctl", "add_vhost", vhost]
    execute_command(cmd_args)

    cmd_args = ["rabbitmqctl", "set_permissions", "-p", vhost, user,
                ".*", ".*", ".*"]
    execute_command(cmd_args)


def clone_rhodecode_code(url, branch, work_dir, source_co):
    """Clones RhodeCode code from git.

    Clones RhodeCode from git and checkouts the specified branch.

    :param url: The URL of the git repository.
    :type str
    :param branch: The name of the branch to checkout.
    :type str
    :param work_dir: The working directory where to clone the code.
    :type str
    :param source_co: The destination directory where the code will be cloned.
    :type str
    """
    source_path = os.path.join(work_dir, source_co)
    if not os.path.exists(source_path):
        cmd_args = ["git", "clone", url, source_co]
        execute_command(cmd_args, work_dir=work_dir)

        cmd_args = ["git", "checkout", branch]
        execute_command(cmd_args, work_dir=source_path)

        cmd_args = ["git", "pull", "origin", branch]
        execute_command(cmd_args, work_dir=source_path)


def set_owners(directory, usr, group=None):
    """Sets the correct ownership on the given directory.

    :param directory: The directory to set the ownership.
    :type str
    :param usr: The name of the user to set the ownership.
    :type str
    :param group: The name of the group to set the ownership. Default to the
    usr parameter.
    :type str
    """
    if not group:
        group = usr
    chown = "%s:%s" % (usr, group)
    cmd_args = ["chown", "-R", chown, directory]
    execute_command(cmd_args)


def set_permissions(file_or_dir, permissions):
    """Sets the permissions on the given path.

    :param file_or_dir: A list of paths to set the permissions.
    :type list
    :param permissions: String containing the permissions as passed to the
    'chmod' command.
    """
    if not isinstance(file_or_dir, list):
        file_or_dir = [file_or_dir]
    for element in file_or_dir:
        cmd_args = ["chmod", "-R", permissions, element]
        execute_command(cmd_args)


def install_rhodecode(work_dir, user=None):
    """Installs RhodeCode on the system.

    :param work_dir: The directory containing RhodeCode setup file.
    :type str
    """
    cmd_args = ["python", "setup.py", "install"]

    if user:
        cmd_args = ["-u", user, "-H"] + cmd_args
        cmd_args.append("--user")
    execute_command(cmd_args, work_dir=work_dir)

def reinstall_rhodecode(work_dir):
    """Re-installs RhodeCode on the system.

    :param work_dir: The directory containing RhodeCode setup file.
    :type str
    """
    cmd_args = ["python", "setup.py", "clean"]
    execute_command(cmd_args, work_dir=work_dir, with_sudo=True)
    cmd_args = ["python", "setup.py", "install"]
    execute_command(cmd_args, work_dir=work_dir, with_sudo=True)


def update_rhodecode(tag, work_dir):
    """Updates RhodeCode code base to the provided tag/branch.

    :param tag: Tag (or branch) to which to update the code base.
    :param work_dir: The directory containing RhodeCode setup file.
    :param source_co: The destination directory where the code is cloned.
    :type str
    """
    cmd_args = ["git", "pull"]
    execute_command(cmd_args, work_dir=work_dir)
    cmd_args = ["git", "checkout", tag]
    execute_command(cmd_args, work_dir=work_dir, with_sudo=True)


def update_database_schema(work_dir, config_file, assume_yes=False):
    """Updates the database schema regardles of the database used.

    :param work_dir: Working directory.
    :type str
    :param config_file: Config file to use, it will tell which db to update.
    :type str
    """
    input_str = None
    if assume_yes:
        input_str = "y"

    cmd_args = ["paster", "upgrade-db", config_file]
    execute_command(cmd_args, work_dir=work_dir, input_str=input_str,
                    continue_on_error=True)


def backup_installation(home_dir):
    """Backup the old code base and installation in home directory.

    :param home_dir: Working directory.
    :type str
    """
    date = datetime.date.today()
    backup_filename = "%s.%s.tar.gz" % (args.rhodecode_checkout_dir,
                                        date.strftime("%Y.%m.%d"))
    cmd_args = ["tar", "czf", backup_filename, args.rhodecode_checkout_dir]
    execute_command(cmd_args, work_dir=home_dir)


def backup_postgres_db(home_dir, db_name, postgres_usr="postgres"):
    """Backup the database as file in home directory.

    :param home_dir: Working directory.
    :type str
    :param config_file: Config file to use, it will tell which db to update.
    :type str
    """
    date = datetime.date.today()
    tempfile_name = "/%s/%s" % ("tmp", DB_BACKUP_FILENAME)
    db_filename = "%s.%s" % (DB_BACKUP_FILENAME, date.strftime("%Y.%m.%d"))
    cmd_args = ["-u", postgres_usr, "pg_dump", db_name, "-f", tempfile_name]
    execute_command(cmd_args, work_dir=home_dir)

    cmd_args = ["cp", tempfile_name, db_filename]
    execute_command(cmd_args, work_dir=home_dir)


def setup_rhodecode(rhodecode_dir, config_file, git_repos, admin_usr,
                    admin_pwd, admin_email, user=None, assume_yes=False):
    """Sets up RhodeCode instance.

    :param rhodecode_dir: The directory where RhodeCode code was checked out.
    :type str
    :param config_file: The path to the production.ini config file.
    :type str
    :param admin_usr: The RhodeCode admin user name.
    :type str
    :param admin_pwd: The RhodeCode admin user password.
    :type str
    :param admin_email: The RhodeCode admin user email.
    :type str
    :param user: The user to run the process as.
    :type str
    :param assume_yes: Tries to automate the process.
    :type bool
    """
    usr_arg = "--user=%s" % admin_usr
    pwd_arg = "--password=%s" % admin_pwd
    email_arg = "--email=%s" % admin_email
    repos = "--repos=%s" % os.path.abspath(git_repos)

    if user:
        cmd_args = ["-u", user, "-H"]

    cmd_args += ["paster", "setup-rhodecode", config_file]
    cmd_args.append(usr_arg)
    cmd_args.append(pwd_arg)
    cmd_args.append(email_arg)
    cmd_args.append(repos)

    input_str = None
    if assume_yes:
        input_str = "y"
    execute_command(cmd_args, work_dir=rhodecode_dir, input_str=input_str)


def install_upstart_conf(no_celery):
    """Installs the upstart conf files for RhodeCode and Celery.

    :param no_celery: If Celery has to be used.
    :type bool
    """
    basedir = os.path.dirname(__file__)
    rhodecode_upstart = os.path.join(basedir, RHODECODE_UPSTART_CONF)
    celeryd_upstart = os.path.join(basedir, CELERY_UPSTART_CONF)

    cmd_args = ["cp", rhodecode_upstart, "/etc/init/rhodecode.conf"]
    execute_command(cmd_args)

    if not no_celery:
        cmd_args = ["cp", celeryd_upstart, "/etc/init/celeryd.conf"]
        execute_command(cmd_args)


def copy_file(source, dest):
    """Copies the a file to the defined destination.

    :param source: Path to the file to copy.
    :param dest: Where to copy the source file.
    """
    cmd_args = ["cp", source, dest]
    execute_command(cmd_args)


def start_service(service):
    """Starts a service.

    Start a service by using the 'service' command.

    :param service: The service to start.
    :type str
    """
    cmd_args = ["service", service, "start"]
    execute_command(cmd_args, continue_on_error=True)


def stop_service(service):
    """Stops a service.

    Stop a service by using the 'service' command.

    :param service: The service to stop.
    :type str
    """
    cmd_args = ["service", service, "stop"]
    execute_command(cmd_args, continue_on_error=True)


def reload_apache_service():
    """Reloads Apache configuration."""
    cmd_args = ["service", "apache2", "reload"]
    execute_command(cmd_args)


def disable_apache_sites(sites):
    """Disables Apache sites.

    :param sites: The list of sites to disable.
    :type list
    """
    if not isinstance(sites, list):
        sites = [sites]

    for site in sites:
        cmd_args = ["a2dissite", site]
        execute_command(cmd_args)


def enable_apache_sites(sites):
    """Enables Apache sites.

    :param sites: The list of sites to enable.
    :type list
    """
    if not isinstance(sites, list):
        sites = [sites]

    for site in sites:
        cmd_args = ["a2ensite", site]
        execute_command(cmd_args)


def enable_apache_modules(modules):
    """Enables Apache modules.

    :param modules: List of modules to enable.
    :type list
    """
    if not isinstance(modules, list):
        modules = [modules]

    for module in modules:
        cmd_args = ["a2enmod", module]
        execute_command(cmd_args)


def print_install_report(args, home_dir, config_file):
    """Prints a final report with all the installation data.

    :param args: The command line arguments.
    """
    print "\n\nRhodeCode Linaro Installation Report\n"

    print "\nRhodeCode Information\n"
    print "\tCode cloned from: %s" % args.rhodecode_git_url
    print "\tInstallation Directory: %s" % home_dir
    print "\tConfiguration file: %s" % config_file
    print "\tData Directory: %s" % args.rhodecode_data_dir
    print "\tRepos Directory: %s" % args.repos_dir
    print "\tAdmin Username: %s" % args.rhodecode_admin_usr
    print "\tAdmin Password: %s" % args.rhodecode_admin_pwd
    print "\tAdmin Email: %s" % args.rhodecode_admin_email

    print "\nDatabase Information\n"
    if args.development:
        print "\tDatabase Backend: SQLite"
        print "\tDatabse Location: Refer to configuration file."
    else:
        print "\tDatabase Backend: PostreSQL"
        print "\tDatabase Name: %s" % args.dbname
        print "\tDatabase Role: %s" % args.postgres_role
        print "\tDatabase Role Password: %s" % args.postgres_role_pwd

    print "\nCelery/RabbitMQ Integration\n"
    print "\tCelery activated: %s" % (not args.no_celery)
    if not args.no_celery:
        print "\tRabbitMQ User: %s" % args.rabbitmq_usr
        print "\tRabbitMQ Password: %s" % args.rabbitmq_pwd
        print "\tRabbitMQ Vhost: %s" % args.rabbitmq_vhost


if __name__ == '__main__':
    args = cli_args()
    check_cli_args(args)

    home_dir = os.path.join("/home", args.rhodecode_usr)
    work_dir = os.path.join(home_dir, args.rhodecode_checkout_dir)
    rhodecode_conf = os.path.join(home_dir,
                                  os.path.basename(args.rhodecode_config))

    if args.update:
        # Stop rhodecode
        stop_service("rhodecode")
        stop_service("celeryd")

        backup_installation(home_dir)
        if not args.development:
            backup_postgres_db(home_dir, args.dbname)

        # Update the rhodecode code base. Reinstall Rhodecode.
        update_rhodecode(args.rhodecode_branch, work_dir)
        reinstall_rhodecode(work_dir)

        # Update database schema.
        update_database_schema(work_dir, rhodecode_conf, True)

        # Start rhodecode and celery.
        start_service("rhodecode")

        if not args.no_celery:
            start_service("celeryd")

        # TODO: start some tests when we implement those.

    else:

        # Setup the necessary user for RhodeCode.
        setup_user(args.rhodecode_usr, home_dir, args.rhodecode_usr)

        # Create the necessary directories to store RhodeCode data and cache.
        directories = [args.rhodecode_data_dir, args.repos_dir,
                       args.rhodecode_log_dir]
        if not args.no_celery:
            directories.append(args.celery_log_dir)

        setup_directories(directories, args.rhodecode_usr)

        # Set the correct permissions to the directories, at least the group
        # should be able to write.
        set_permissions(directories, "g+w")

        # Take git-core package from Launchpad PPA of git maintainers.
        #install_git_from_ppa(assume_yes=args.assume_yes)

        # Install all the required packages from the default Ubuntu sources.
        if args.development:
            REQUIRED_PACKAGES.append(SQLITE_DB)
        else:
            REQUIRED_PACKAGES += POSTGRESQL_DB

        if not args.no_celery:
            REQUIRED_PACKAGES += CELERY_REQUIRED_PACKAGES

        install_packages(REQUIRED_PACKAGES, assume_yes=args.assume_yes)

        # Install packages through PIP
        # install_pip_packages(PIP_PACKAGES)

        if not args.development:
            create_postgresql_role(args.postgres_role, args.postgres_role_pwd)
            create_postgresql_db(args.dbname, args.postgres_role)

        if not args.no_celery:
            setup_rabbitmq_server(args.rabbitmq_usr,
                                  args.rabbitmq_pwd,
                                  args.rabbitmq_vhost)

        clone_rhodecode_code(args.rhodecode_git_url,
                             args.rhodecode_branch,
                             home_dir,
                             args.rhodecode_checkout_dir)

        # Need to set the correct owners of the directory.
        set_owners(work_dir, args.rhodecode_usr)
        install_rhodecode(work_dir, args.rhodecode_usr)

        copy_file(args.rhodecode_config, home_dir)
        set_owners(rhodecode_conf, args.rhodecode_usr)

        setup_rhodecode(work_dir,
                        rhodecode_conf,
                        args.repos_dir,
                        args.rhodecode_admin_usr,
                        args.rhodecode_admin_pwd,
                        args.rhodecode_admin_email,
                        user=args.rhodecode_usr,
                        assume_yes=args.assume_yes)

        # Apache configurations.
        apache_conf = os.path.abspath(args.apache_conf)
        copy_file(apache_conf, args.apache_website_dir)

        disable_apache_sites(APACHE_DISABLE_SITES)
        enable_apache_modules(APACHE_ENABLE_MODULES)
        enable_apache_sites(os.path.basename(apache_conf))
        reload_apache_service()

        # Install upstart scripts for Celery and RhodeCode
        install_upstart_conf(args.no_celery)
        start_service("rhodecode")

        if not args.no_celery:
            start_service("celeryd")

        print_install_report(args, home_dir, rhodecode_conf)
        # save_install_args(args, home_dir, rhodecode_conf)