Add common part with DevopPortal

The services definitions which are located at metadata/service/services
will be moved onto the system level, to be re-used in particular
components.

Change-Id: I227638b7a486c156578e5b0d57eb6eb4d9854a89
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..1043fbe
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,118 @@
+DESTDIR=/
+SALTENVDIR=/usr/share/salt-formulas/env
+RECLASSDIR=/usr/share/salt-formulas/reclass
+FORMULANAME=$(shell grep name: metadata.yml|head -1|cut -d : -f 2|grep -Eo '[a-z0-9\-\_]*')
+VERSION=$(shell grep version: metadata.yml|head -1|cut -d : -f 2|grep -Eo '[a-z0-9\.\-\_]*')
+VERSION_MAJOR := $(shell echo $(VERSION)|cut -d . -f 1-2)
+VERSION_MINOR := $(shell echo $(VERSION)|cut -d . -f 3)
+
+NEW_MAJOR_VERSION ?= $(shell date +%Y.%m|sed 's,\.0,\.,g')
+NEW_MINOR_VERSION ?= $(shell /bin/bash -c 'echo $$[ $(VERSION_MINOR) + 1 ]')
+
+MAKE_PID := $(shell echo $$PPID)
+JOB_FLAG := $(filter -j%, $(subst -j ,-j,$(shell ps T | grep "^\s*$(MAKE_PID).*$(MAKE)")))
+
+ifneq ($(subst -j,,$(JOB_FLAG)),)
+JOBS := $(subst -j,,$(JOB_FLAG))
+else
+JOBS := 1
+endif
+
+KITCHEN_LOCAL_YAML?=.kitchen.yml
+KITCHEN_OPTS?="--concurrency=$(JOBS)"
+KITCHEN_OPTS_CREATE?=""
+KITCHEN_OPTS_CONVERGE?=""
+KITCHEN_OPTS_VERIFY?=""
+KITCHEN_OPTS_TEST?=""
+
+all:
+	@echo "make install - Install into DESTDIR"
+	@echo "make test    - Run tests"
+	@echo "make kitchen - Run Kitchen CI tests (create, converge, verify)"
+	@echo "make clean   - Cleanup after tests run"
+	@echo "make release-major  - Generate new major release"
+	@echo "make release-minor  - Generate new minor release"
+	@echo "make changelog      - Show changes since last release"
+
+install:
+	# Formula
+	[ -d $(DESTDIR)/$(SALTENVDIR) ] || mkdir -p $(DESTDIR)/$(SALTENVDIR)
+	cp -a $(FORMULANAME) $(DESTDIR)/$(SALTENVDIR)/
+	[ ! -d _modules ] || cp -a _modules $(DESTDIR)/$(SALTENVDIR)/
+	[ ! -d _states ] || cp -a _states $(DESTDIR)/$(SALTENVDIR)/ || true
+	[ ! -d _grains ] || cp -a _grains $(DESTDIR)/$(SALTENVDIR)/ || true
+	# Metadata
+	[ -d $(DESTDIR)/$(RECLASSDIR)/service/$(FORMULANAME) ] || mkdir -p $(DESTDIR)/$(RECLASSDIR)/service/$(FORMULANAME)
+	cp -a metadata/service/* $(DESTDIR)/$(RECLASSDIR)/service/$(FORMULANAME)
+
+test:
+	[ ! -d tests ] || (cd tests; ./run_tests.sh)
+
+release-major: check-changes
+	@echo "Current version is $(VERSION), new version is $(NEW_MAJOR_VERSION)"
+	@[ $(VERSION_MAJOR) != $(NEW_MAJOR_VERSION) ] || (echo "Major version $(NEW_MAJOR_VERSION) already released, nothing to do. Do you want release-minor?" && exit 1)
+	echo "$(NEW_MAJOR_VERSION)" > VERSION
+	sed -i 's,version: .*,version: "$(NEW_MAJOR_VERSION)",g' metadata.yml
+	[ ! -f debian/changelog ] || dch -v $(NEW_MAJOR_VERSION) -m --force-distribution -D `dpkg-parsechangelog -S Distribution` "New version"
+	make genchangelog-$(NEW_MAJOR_VERSION)
+	(git add -u; git commit -m "Version $(NEW_MAJOR_VERSION)")
+	git tag -s -m $(NEW_MAJOR_VERSION) $(NEW_MAJOR_VERSION)
+
+release-minor: check-changes
+	@echo "Current version is $(VERSION), new version is $(VERSION_MAJOR).$(NEW_MINOR_VERSION)"
+	echo "$(VERSION_MAJOR).$(NEW_MINOR_VERSION)" > VERSION
+	sed -i 's,version: .*,version: "$(VERSION_MAJOR).$(NEW_MINOR_VERSION)",g' metadata.yml
+	[ ! -f debian/changelog ] || dch -v $(VERSION_MAJOR).$(NEW_MINOR_VERSION) -m --force-distribution -D `dpkg-parsechangelog -S Distribution` "New version"
+	make genchangelog-$(VERSION_MAJOR).$(NEW_MINOR_VERSION)
+	(git add -u; git commit -m "Version $(VERSION_MAJOR).$(NEW_MINOR_VERSION)")
+	git tag -s -m $(NEW_MAJOR_VERSION) $(VERSION_MAJOR).$(NEW_MINOR_VERSION)
+
+check-changes:
+	@git log --pretty=oneline --decorate $(VERSION)..HEAD | grep -Eqc '.*' || (echo "No new changes since version $(VERSION)"; exit 1)
+
+changelog:
+	git log --pretty=short --invert-grep --grep="Merge pull request" --decorate $(VERSION)..HEAD
+
+genchangelog: genchangelog-$(VERSION_MAJOR).$(NEW_MINOR_VERSION)
+
+genchangelog-%:
+	$(eval NEW_VERSION := $(patsubst genchangelog-%,%,$@))
+	(echo "=========\nChangelog\n=========\n"; \
+	(echo $(NEW_VERSION);git tag) | sort -r | grep -E '^[0-9\.]+' | while read i; do \
+	    cur=$$i; \
+	    test $$i = $(NEW_VERSION) && i=HEAD; \
+	    prev=`(echo $(NEW_VERSION);git tag)|sort|grep -E '^[0-9\.]+'|grep -B1 "$$cur\$$"|head -1`; \
+	    echo "Version $$cur\n=============================\n"; \
+	    git log --pretty=short --invert-grep --grep="Merge pull request" --decorate $$prev..$$i; \
+	    echo; \
+	done) > CHANGELOG.rst
+
+kitchen-check:
+	@[ -e $(KITCHEN_LOCAL_YAML) ] || (echo "Kitchen tests not available, there's no $(KITCHEN_LOCAL_YAML)." && exit 1)
+
+kitchen: kitchen-check kitchen-create kitchen-converge kitchen-verify kitchen-list
+
+kitchen-create: kitchen-check
+	kitchen create ${KITCHEN_OPTS} ${KITCHEN_OPTS_CREATE}
+	[ "$(shell echo $(KITCHEN_LOCAL_YAML)|grep -Eo docker)" = "docker" ] || sleep 120
+
+kitchen-converge: kitchen-check
+	kitchen converge ${KITCHEN_OPTS} ${KITCHEN_OPTS_CONVERGE} &&\
+	kitchen converge ${KITCHEN_OPTS} ${KITCHEN_OPTS_CONVERGE}
+
+kitchen-verify: kitchen-check
+	[ ! -d tests/integration ] || kitchen verify -t tests/integration ${KITCHEN_OPTS} ${KITCHEN_OPTS_VERIFY}
+	[ -d tests/integration ]   || kitchen verify ${KITCHEN_OPTS} ${KITCHEN_OPTS_VERIFY}
+
+kitchen-test: kitchen-check
+	[ ! -d tests/integration ] || kitchen test -t tests/integration ${KITCHEN_OPTS} ${KITCHEN_OPTS_TEST}
+	[ -d tests/integration ]   || kitchen test ${KITCHEN_OPTS} ${KITCHEN_OPTS_TEST}
+
+kitchen-list: kitchen-check
+	kitchen list
+
+clean:
+	[ ! -x "$(shell which kitchen)" ] || kitchen destroy
+	[ ! -d .kitchen ] || rm -rf .kitchen
+	[ ! -d tests/build ] || rm -rf tests/build
+	[ ! -d build ] || rm -rf build
diff --git a/_modules/devops_utils.py b/_modules/devops_utils.py
new file mode 100644
index 0000000..012093d
--- /dev/null
+++ b/_modules/devops_utils.py
@@ -0,0 +1,12 @@
+def iter_items(keys, dict):
+    """Iterator over keys and yeilds items from dict.
+
+    Iterates over keys and yeilds tuples of a key and a value only if key is
+    presented in dict.
+
+    :param keys: A list of keys to iterate over.
+    :param dict: A dict to iterate over.
+    """
+    for key in keys:
+        if key in dict:
+            yield (key, dict[key])
diff --git a/devops_portal/control.sls b/devops_portal/control.sls
new file mode 100644
index 0000000..eaaac62
--- /dev/null
+++ b/devops_portal/control.sls
@@ -0,0 +1,36 @@
+{%- from "devops_portal/map.jinja" import control with context %}
+{%- if control.enabled %}
+
+devops_portal_dirs:
+  file.directory:
+    - names:
+      - /srv/oss/devops_portal/nginx
+      - /srv/oss/devops_portal/config
+    - user: root
+    - group: root
+    - mode: 0755
+    - makedirs: true
+
+devops_portal_nginx_conf:
+  file.managed:
+    - name: /srv/oss/devops_portal/nginx/nginx.conf
+    - source: salt://devops_portal/files/nginx.conf
+    - template: jinja
+    - user: root
+    - group: root
+    - mode: 0644
+    - require:
+      - file: devops_portal_dirs
+
+devops_portal_config:
+  file.managed:
+    - name: /srv/oss/devops_portal/config/config.json
+    - source: salt://devops_portal/files/config.json
+    - template: jinja
+    - user: root
+    - group: root
+    - mode: 0640
+    - require:
+      - file: devops_portal_dirs
+
+{%- endif %}
diff --git a/devops_portal/files/config.json b/devops_portal/files/config.json
new file mode 100644
index 0000000..bb07fae
--- /dev/null
+++ b/devops_portal/files/config.json
@@ -0,0 +1,26 @@
+{%- from "devops_portal/map.jinja" import control with context -%}
+{%- from "devops_portal/map.jinja" import services with context -%}
+{%- macro credentials(parameters) -%}
+{%- set keys = ['token', 'username', 'password'] -%}
+"credentials": {
+{%- for key, value in salt['devops_utils.iter_items'](keys, parameters) %}
+  {%- if not loop.first %},{% endif %}
+  "{{ key }}": "{{ value }}"
+{%- endfor %}
+}
+{%- endmacro %}
+{
+  "services": {
+  {%- for service_name, service in salt['devops_utils.iter_items'](services, control.services) %}
+    {%- if not loop.first %},{% endif -%}
+    {%- if service|length() > 0 and service.enabled %}
+    "{{ service_name }}": {
+      "endpoint": "{{ service.endpoint }}"
+      {%- if service.credentials is defined and service.credentials|length() > 0 -%},
+      {{ credentials(service.credentials)|indent(width=8) }}
+      {%- endif %}
+    }
+    {%- endif %}
+  {%- endfor %}
+  }
+}
diff --git a/devops_portal/files/nginx.conf b/devops_portal/files/nginx.conf
new file mode 100644
index 0000000..5813f5d
--- /dev/null
+++ b/devops_portal/files/nginx.conf
@@ -0,0 +1,49 @@
+{%- from "devops_portal/map.jinja" import control with context -%}
+{%- from "devops_portal/map.jinja" import services with context -%}
+daemon off;
+
+worker_processes 1;
+
+error_log /dev/stderr;
+pid /var/run/nginx/nginx.pid;
+
+events {
+    worker_connections 1024;
+}
+
+http {
+    include /etc/nginx/mime.types;
+
+    sendfile on;
+
+    access_log /dev/stdout;
+
+    server {
+        listen 0.0.0.0:{{ control.container.container_port }} default_server;
+
+        root /opt/devops-portal/;
+
+        gzip on;
+        gzip_min_length 1000;
+        gzip_types
+            text/plain
+            text/css
+            application/json
+            application/javascript
+            application/x-javascript;
+
+        location / {
+            try_files $uri /index.html;
+        }
+
+{%- for service_name in services %}
+{%- set service = control.services[service_name]|default({}) %}
+{%- if service.enabled and service.configure_proxy|default(False) %}
+
+        location /api/{{ service_name }} {
+            proxy_pass {{ service.endpoint }};
+        }
+{%- endif %}
+{%- endfor %}
+    }
+}
diff --git a/devops_portal/init.sls b/devops_portal/init.sls
new file mode 100644
index 0000000..00649c7
--- /dev/null
+++ b/devops_portal/init.sls
@@ -0,0 +1,7 @@
+{%- if pillar.devops_portal is defined %}
+include:
+{%- if pillar.devops_portal.control is defined %}
+  - devops_portal.control
+  - devops_portal.setup
+{%- endif %}
+{%- endif %}
diff --git a/devops_portal/map.jinja b/devops_portal/map.jinja
new file mode 100644
index 0000000..935a0db
--- /dev/null
+++ b/devops_portal/map.jinja
@@ -0,0 +1,13 @@
+{% set control = salt['pillar.get']('devops_portal:setup') %}
+{% set control = salt['pillar.get']('devops_portal:control') %}
+
+{% set services = [
+'artifactory',
+'elasticsearch',
+'gerrit',
+'grafana',
+'jenkins',
+'kibana',
+'riverdelta',
+'rundeck',
+] %}
diff --git a/devops_portal/setup/init.sls b/devops_portal/setup/init.sls
new file mode 100644
index 0000000..1b43923
--- /dev/null
+++ b/devops_portal/setup/init.sls
@@ -0,0 +1 @@
+include:
diff --git a/metadata.yml b/metadata.yml
new file mode 100644
index 0000000..d0a300a
--- /dev/null
+++ b/metadata.yml
@@ -0,0 +1,3 @@
+name: "devops_portal"
+version: "0.1"
+source: "https://github.com/tcpcloud/salt-formula-devops-portal"
diff --git a/metadata/service/control/single.yml b/metadata/service/control/single.yml
new file mode 100644
index 0000000..6d43062
--- /dev/null
+++ b/metadata/service/control/single.yml
@@ -0,0 +1,15 @@
+applications:
+  - devops_portal
+parameters:
+  _param:
+    devops_portal_image: docker-sandbox.sandbox.mirantis.net/ikharin/oss/devops-portal:latest
+    devops_portal_external_port: 8000
+  devops_portal:
+    control:
+      enabled: true
+      container:
+        image: ${_param:devops_portal_image}
+        external_ip: ${_param:devops_portal_external_ip}
+        external_port: ${_param:devops_portal_external_port}
+        container_port: 8000
+      services: {}
diff --git a/metadata/service/services/artifactory.yml b/metadata/service/services/artifactory.yml
new file mode 100644
index 0000000..9ca4ca6
--- /dev/null
+++ b/metadata/service/services/artifactory.yml
@@ -0,0 +1,7 @@
+parameters:
+  devops_portal:
+    control:
+      services:
+        artifactory:
+          enabled: true
+          endpoint: ${_param:devops_portal_artifactory_url}
diff --git a/metadata/service/services/elasticsearch.yml b/metadata/service/services/elasticsearch.yml
new file mode 100644
index 0000000..179d95f
--- /dev/null
+++ b/metadata/service/services/elasticsearch.yml
@@ -0,0 +1,8 @@
+parameters:
+  devops_portal:
+    control:
+      services:
+        elasticsearch:
+          enabled: true
+          endpoint: ${_param:devops_portal_elasticsearch_url}
+          configure_proxy: true
diff --git a/metadata/service/services/gerrit.yml b/metadata/service/services/gerrit.yml
new file mode 100644
index 0000000..5c73533
--- /dev/null
+++ b/metadata/service/services/gerrit.yml
@@ -0,0 +1,7 @@
+parameters:
+  devops_portal:
+    control:
+      services:
+        gerrit:
+          enabled: true
+          endpoint: ${_param:devops_portal_gerrit_url}
diff --git a/metadata/service/services/grafana.yml b/metadata/service/services/grafana.yml
new file mode 100644
index 0000000..fd3d79a
--- /dev/null
+++ b/metadata/service/services/grafana.yml
@@ -0,0 +1,7 @@
+parameters:
+  devops_portal:
+    control:
+      services:
+        grafana:
+          enabled: true
+          endpoint: ${_param:devops_portal_grafana_url}
diff --git a/metadata/service/services/jenkins.yml b/metadata/service/services/jenkins.yml
new file mode 100644
index 0000000..8bda0b3
--- /dev/null
+++ b/metadata/service/services/jenkins.yml
@@ -0,0 +1,10 @@
+parameters:
+  devops_portal:
+    control:
+      services:
+        jenkins:
+          enabled: true
+          endpoint: ${_param:devops_portal_jenkins_url}
+          credentials:
+            username: ${_param:devops_portal_jenkins_username}
+            password: ${_param:devops_portal_jenkins_password}
diff --git a/metadata/service/services/kibana.yml b/metadata/service/services/kibana.yml
new file mode 100644
index 0000000..ed7abe9
--- /dev/null
+++ b/metadata/service/services/kibana.yml
@@ -0,0 +1,7 @@
+parameters:
+  devops_portal:
+    control:
+      services:
+        kibana:
+          enabled: true
+          endpoint: ${_param:devops_portal_kibana_url}
diff --git a/metadata/service/services/riverdelta.yml b/metadata/service/services/riverdelta.yml
new file mode 100644
index 0000000..252d864
--- /dev/null
+++ b/metadata/service/services/riverdelta.yml
@@ -0,0 +1,8 @@
+parameters:
+  devops_portal:
+    control:
+      services:
+        riverdelta:
+          enabled: true
+          endpoint: ${_param:devops_portal_riverdelta_url}
+
diff --git a/metadata/service/services/rundeck.yml b/metadata/service/services/rundeck.yml
new file mode 100644
index 0000000..b1474cc
--- /dev/null
+++ b/metadata/service/services/rundeck.yml
@@ -0,0 +1,12 @@
+parameters:
+  devops_portal:
+    control:
+      services:
+        rundeck:
+          enabled: true
+          endpoint: ${_param:devops_portal_rundeck_url}
+          configure_proxy: true
+          credentials:
+            token: ${_param:devops_portal_rundeck_token}
+            username: ${_param:devops_portal_rundeck_username}
+            password: ${_param:devops_portal_rundeck_password}
diff --git a/metadata/service/support.yml b/metadata/service/support.yml
new file mode 100644
index 0000000..4facf47
--- /dev/null
+++ b/metadata/service/support.yml
@@ -0,0 +1,11 @@
+parameters:
+  devops_portal:
+    _support:
+      collectd:
+        enabled: false
+      heka:
+        enabled: false
+      sensu:
+        enabled: false
+      sphinx:
+        enabled: false
diff --git a/tests/run_tests.sh b/tests/run_tests.sh
new file mode 100755
index 0000000..8c07e58
--- /dev/null
+++ b/tests/run_tests.sh
@@ -0,0 +1,163 @@
+#!/usr/bin/env bash
+
+set -e
+[ -n "$DEBUG" ] && set -x
+
+CURDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+METADATA=${CURDIR}/../metadata.yml
+FORMULA_NAME=$(cat $METADATA | python -c "import sys,yaml; print yaml.load(sys.stdin)['name']")
+
+## Overrideable parameters
+PILLARDIR=${PILLARDIR:-${CURDIR}/pillar}
+BUILDDIR=${BUILDDIR:-${CURDIR}/build}
+VENV_DIR=${VENV_DIR:-${BUILDDIR}/virtualenv}
+DEPSDIR=${BUILDDIR}/deps
+
+SALT_FILE_DIR=${SALT_FILE_DIR:-${BUILDDIR}/file_root}
+SALT_PILLAR_DIR=${SALT_PILLAR_DIR:-${BUILDDIR}/pillar_root}
+SALT_CONFIG_DIR=${SALT_CONFIG_DIR:-${BUILDDIR}/salt}
+SALT_CACHE_DIR=${SALT_CACHE_DIR:-${SALT_CONFIG_DIR}/cache}
+
+SALT_OPTS="${SALT_OPTS} --retcode-passthrough --local -c ${SALT_CONFIG_DIR} --log-file=/dev/null"
+
+if [ "x${SALT_VERSION}" != "x" ]; then
+    PIP_SALT_VERSION="==${SALT_VERSION}"
+fi
+
+## Functions
+log_info() {
+    echo "[INFO] $*"
+}
+
+log_err() {
+    echo "[ERROR] $*" >&2
+}
+
+setup_virtualenv() {
+    log_info "Setting up Python virtualenv"
+    virtualenv $VENV_DIR
+    source ${VENV_DIR}/bin/activate
+    pip install salt${PIP_SALT_VERSION}
+}
+
+setup_pillar() {
+    [ ! -d ${SALT_PILLAR_DIR} ] && mkdir -p ${SALT_PILLAR_DIR}
+    echo "base:" > ${SALT_PILLAR_DIR}/top.sls
+    for pillar in ${PILLARDIR}/*; do
+        state_name=$(basename ${pillar%.sls})
+        echo -e "  ${state_name}:\n    - ${state_name}" >> ${SALT_PILLAR_DIR}/top.sls
+    done
+}
+
+setup_salt() {
+    [ ! -d ${SALT_FILE_DIR} ] && mkdir -p ${SALT_FILE_DIR}
+    [ ! -d ${SALT_CONFIG_DIR} ] && mkdir -p ${SALT_CONFIG_DIR}
+    [ ! -d ${SALT_CACHE_DIR} ] && mkdir -p ${SALT_CACHE_DIR}
+
+    echo "base:" > ${SALT_FILE_DIR}/top.sls
+    for pillar in ${PILLARDIR}/*.sls; do
+        state_name=$(basename ${pillar%.sls})
+        echo -e "  ${state_name}:\n    - ${FORMULA_NAME}" >> ${SALT_FILE_DIR}/top.sls
+    done
+
+    cat << EOF > ${SALT_CONFIG_DIR}/minion
+file_client: local
+cachedir: ${SALT_CACHE_DIR}
+verify_env: False
+minion_id_caching: False
+
+file_roots:
+  base:
+  - ${SALT_FILE_DIR}
+  - ${CURDIR}/..
+  - /usr/share/salt-formulas/env
+
+pillar_roots:
+  base:
+  - ${SALT_PILLAR_DIR}
+  - ${PILLARDIR}
+EOF
+}
+
+fetch_dependency() {
+    dep_name="$(echo $1|cut -d : -f 1)"
+    dep_source="$(echo $1|cut -d : -f 2-)"
+    dep_root="${DEPSDIR}/$(basename $dep_source .git)"
+    dep_metadata="${dep_root}/metadata.yml"
+
+    [ -d /usr/share/salt-formulas/env/${dep_name} ] && log_info "Dependency $dep_name already present in system-wide salt env" && return 0
+    [ -d $dep_root ] && log_info "Dependency $dep_name already fetched" && return 0
+
+    log_info "Fetching dependency $dep_name"
+    [ ! -d ${DEPSDIR} ] && mkdir -p ${DEPSDIR}
+    git clone $dep_source ${DEPSDIR}/$(basename $dep_source .git)
+    ln -s ${dep_root}/${dep_name} ${SALT_FILE_DIR}/${dep_name}
+
+    METADATA="${dep_metadata}" install_dependencies
+}
+
+install_dependencies() {
+    grep -E "^dependencies:" ${METADATA} >/dev/null || return 0
+    (python - | while read dep; do fetch_dependency "$dep"; done) << EOF
+import sys,yaml
+for dep in yaml.load(open('${METADATA}', 'ro'))['dependencies']:
+    print '%s:%s' % (dep["name"], dep["source"])
+EOF
+}
+
+clean() {
+    log_info "Cleaning up ${BUILDDIR}"
+    [ -d ${BUILDDIR} ] && rm -rf ${BUILDDIR} || exit 0
+}
+
+salt_run() {
+    [ -e ${VEN_DIR}/bin/activate ] && source ${VENV_DIR}/bin/activate
+    salt-call ${SALT_OPTS} $*
+}
+
+prepare() {
+    [ -d ${BUILDDIR} ] && mkdir -p ${BUILDDIR}
+
+    which salt-call || setup_virtualenv
+    setup_pillar
+    setup_salt
+    install_dependencies
+}
+
+run() {
+    for pillar in ${PILLARDIR}/*.sls; do
+        state_name=$(basename ${pillar%.sls})
+        salt_run --id=${state_name} state.show_sls ${FORMULA_NAME} || (log_err "Execution of ${FORMULA_NAME}.${state_name} failed"; exit 1)
+    done
+}
+
+_atexit() {
+    RETVAL=$?
+    trap true INT TERM EXIT
+
+    if [ $RETVAL -ne 0 ]; then
+        log_err "Execution failed"
+    else
+        log_info "Execution successful"
+    fi
+    return $RETVAL
+}
+
+## Main
+trap _atexit INT TERM EXIT
+
+case $1 in
+    clean)
+        clean
+        ;;
+    prepare)
+        prepare
+        ;;
+    run)
+        run
+        ;;
+    *)
+        prepare
+        run
+        ;;
+esac