DogTag initial commit

This patch adds formula to install and configure DogTag.

Change-Id: Ibb19fff599c8c04ea431f4c02d2230c2e41f15e9
Related-PROD: PROD-15641
diff --git a/.kitchen.yml b/.kitchen.yml
new file mode 100644
index 0000000..6f32d1d
--- /dev/null
+++ b/.kitchen.yml
@@ -0,0 +1,47 @@
+---
+driver:
+  name: docker
+  hostname: dogtag.ci.local
+  use_sudo: true
+
+
+provisioner:
+  name: salt_solo
+  salt_install: bootstrap
+  salt_bootstrap_url: https://bootstrap.saltstack.com
+  salt_version: latest
+  require_chef: false
+  log_level: debug
+  formula: dogtag
+  grains:
+    noservices: True
+    service: service
+    systemd: False
+    providers:
+      service: service
+  state_top:
+    base:
+      "*":
+        - dogtag
+  pillars:
+    top.sls:
+      base:
+        "*":
+          - dogtag
+
+verifier:
+  name: inspec
+  sudo: true
+
+platforms:
+  - name: <%= ENV['PLATFORM'] || 'ubuntu-xenial' %>
+    driver_config:
+      image: <%= ENV['PLATFORM'] || 'trevorj/salty-whales:xenial' %>
+      platform: ubuntu
+
+suites:
+
+  - name: dogtag
+    provisioner:
+      pillars-from-files:
+        dogtag.sls: tests/pillar/dogtag_single.sls
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..03a7f7b
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,38 @@
+sudo: required
+services:
+  - docker
+
+install:
+  - pip install PyYAML
+  - pip install virtualenv
+  - |
+    test -e Gemfile || cat <<EOF > Gemfile
+    source 'https://rubygems.org'
+    gem 'rake'
+    gem 'test-kitchen'
+    gem 'kitchen-docker'
+    gem 'kitchen-inspec'
+    gem 'inspec'
+    gem 'kitchen-salt', :git => 'https://github.com/salt-formulas/kitchen-salt.git'
+  - bundle install
+
+env:
+  - PLATFORM=trevorj/salty-whales:xenial
+
+before_script:
+  - set -o pipefail
+  - make test | tail
+
+script:
+  - test ! -e .kitchen.yml || bundle exec kitchen test -t tests/integration
+
+notifications:
+  webhooks:
+    urls:
+      - https://webhooks.gitter.im/e/6123573504759330786b
+    on_success: change  # options: [always|never|change] default: always
+    on_failure: never  # options: [always|never|change] default: always
+    on_start: never     # options: [always|never|change] default: always
+    on_cancel: never    # options: [always|never|change] default: always
+    on_error: never    # options: [always|never|change] default: always
+  email: false
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
new file mode 100644
index 0000000..806d38a
--- /dev/null
+++ b/CHANGELOG.rst
@@ -0,0 +1,6 @@
+Dogtag formula
+=========================================
+
+0.1 (2017-11-07)
+
+- Initial formula setup
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..ea2818f
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,13 @@
+Copyright (c) Mirantis Inc.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..4a83bf8
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,35 @@
+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\-\_]*')
+
+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
+
+all:
+	@echo "make install - Install into DESTDIR"
+	@echo "make test    - Run tests"
+	@echo "make clean   - Cleanup after tests run"
+
+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
+	# 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)
+
+clean:
+	[ ! -d tests/build ] || rm -rf tests/build
+	[ ! -d build ] || rm -rf build
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..0faa55f
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,53 @@
+
+==================================
+dogtag
+==================================
+
+Service dogtag description
+
+Sample pillars
+==============
+
+Single dogtag service
+
+.. code-block:: yaml
+  dogtag:
+    server:
+      ldap_hostname: hostname.somedomain.com
+      export_pem_file_path: /etc/barbican/kra_admin_cert.pem
+
+Define paramters for all Dogtag subsystems
+=============
+.. code-block:: yaml
+  dogtag:
+    server:
+      ldap_hostname: hostname.somedomain.com
+      ldap_dn_password: ds_password
+      export_pem_file_path: /etc/barbican/kra_admin_cert.pem
+      default_config_options:
+        pki_ds_hostname: hostname.somedomain.com
+        pki_admin_password: workshop
+        pki_ds_password: ds_password
+
+
+Define paramters for specific DogTag subsystem
+=============
+.. code-block:: yaml
+  dogtag:
+    server:
+      export_pem_file_path: /etc/barbican/kra_admin_cert.pem
+      subsystems:
+        KRA:
+          pki_admin_name: krakraadmin
+
+
+Disable specific DogTag subsystem
+=============
+.. code-block:: yaml
+  dogtag:
+    server:
+      export_pem_file_path: /etc/barbican/kra_admin_cert.pem
+      subsystems:
+        TPS:
+          enabled: False
+
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..49d5957
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.1
diff --git a/debian/changelog b/debian/changelog
new file mode 100644
index 0000000..3f6bd95
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,5 @@
+salt-formula-dogtag (0.1) trusty; urgency=medium
+
+  * Initial release
+
+ -- Oleg Iurchenko <oiurchenko@mirantis.com>  Tue, 11 Nov 2017 17:35:41 +0200
diff --git a/debian/compat b/debian/compat
new file mode 100644
index 0000000..ec63514
--- /dev/null
+++ b/debian/compat
@@ -0,0 +1 @@
+9
diff --git a/debian/control b/debian/control
new file mode 100644
index 0000000..c77855b
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,15 @@
+Source: salt-formula-dogtag
+Maintainer: Oleg Iurchenko <oiurchenko@mirantis.com>
+Section: admin
+Priority: optional
+Build-Depends: debhelper (>= 9), salt-master, python, python-yaml
+Standards-Version: 3.9.6
+Homepage: https://www.mirantis.com/
+Vcs-Browser: https://github.com/salt-formulas/salt-formula-dogtag
+Vcs-Git: https://github.com/salt-formulas/salt-formula-dogtag.git
+
+Package: salt-formula-dogtag
+Architecture: all
+Depends: ${misc:Depends}, salt-master, reclass
+Description: dogtag salt formula
+ Install and configure DogTag system.
diff --git a/debian/copyright b/debian/copyright
new file mode 100644
index 0000000..efc9404
--- /dev/null
+++ b/debian/copyright
@@ -0,0 +1,15 @@
+Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
+Upstream-Name: salt-formula-dogtag
+Upstream-Contact:
+Source: https://github.com/salt-formulas/salt-formula-dogtag
+
+Files: *
+Copyright: Mirantis Inc.
+License: Apache-2.0
+  Copyright (C) Mirantis Inc.
+  .
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  .
+  On a Debian system you can find a copy of this license in
+  /usr/share/common-licenses/Apache-2.0.
diff --git a/debian/docs b/debian/docs
new file mode 100644
index 0000000..d585829
--- /dev/null
+++ b/debian/docs
@@ -0,0 +1,3 @@
+README.rst
+CHANGELOG.rst
+VERSION
diff --git a/debian/rules b/debian/rules
new file mode 100755
index 0000000..abde6ef
--- /dev/null
+++ b/debian/rules
@@ -0,0 +1,5 @@
+#!/usr/bin/make -f
+
+%:
+	dh $@
+
diff --git a/debian/source/format b/debian/source/format
new file mode 100644
index 0000000..89ae9db
--- /dev/null
+++ b/debian/source/format
@@ -0,0 +1 @@
+3.0 (native)
diff --git a/doc/source/conf.py b/doc/source/conf.py
new file mode 100644
index 0000000..28f16cb
--- /dev/null
+++ b/doc/source/conf.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import sys
+
+sys.path.insert(0, os.path.abspath('../..'))
+# -- General configuration ----------------------------------------------------
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = [
+    'sphinx.ext.autodoc',
+]
+
+# autodoc generation is a bit aggressive and a nuisance when doing heavy
+# text edit cycles.
+# execute "export SPHINX_DEBUG=1" in your terminal to disable
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'salt-formula-dogtag'
+copyright = u'2017, Mirantis Inc.'
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+add_module_names = True
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# -- Options for HTML output --------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages.  Major themes that come with
+# Sphinx are currently 'default' and 'sphinxdoc'.
+# html_theme_path = ["."]
+# html_theme = '_theme'
+# html_static_path = ['static']
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = '%sdoc' % project
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass
+# [howto/manual]).
+latex_documents = [
+    ('index',
+     '%s.tex' % project,
+     u'%s Documentation' % project,
+     u'OpenStack Foundation', 'manual'),
+]
+
+# Example configuration for intersphinx: refer to the Python standard library.
+# intersphinx_mapping = {'http://docs.python.org/': None}
diff --git a/doc/source/index.rst b/doc/source/index.rst
new file mode 100644
index 0000000..a6210d3
--- /dev/null
+++ b/doc/source/index.rst
@@ -0,0 +1 @@
+.. include:: ../../README.rst
diff --git a/dogtag/files/389-ds_setup.inf b/dogtag/files/389-ds_setup.inf
new file mode 100644
index 0000000..be764f4
--- /dev/null
+++ b/dogtag/files/389-ds_setup.inf
@@ -0,0 +1,11 @@
+{%- from "dogtag/map.jinja" import server with context -%}
+[General]
+FullMachineName = {{ server.ldap_hostname|default('localhost') }}
+SuiteSpotUserID = dirsrv
+SuiteSpotGroup = dirsrv
+[slapd]
+ServerPort = {{ server.ldap_server_port|default(389) }}
+ServerIdentifier = pki-tomcat
+Suffix = {{ server.ldap_dc|default('dc=example,dc=com') }}
+RootDN = {{ server.ldap_dn|default('cn=Directory Manager') }}
+RootDNPwd = {{ server.ldap_dn_password|default('PASSWORD') }}
diff --git a/dogtag/files/dogtag.cfg b/dogtag/files/dogtag.cfg
new file mode 100644
index 0000000..67934e3
--- /dev/null
+++ b/dogtag/files/dogtag.cfg
@@ -0,0 +1,13 @@
+{%- from "dogtag/map.jinja" import server with context -%}
+[DEFAULT]
+{%- for conf_opt_name, conf_opt_value in server.default_config_options.iteritems() %}
+{{ conf_opt_name }} = {{ conf_opt_value }}
+{%- endfor %}
+{%- for subsystem_name, subsystem_params in server.subsystems.iteritems() %}
+[{{ subsystem_name }}]
+{%- for key, value in subsystem_params.iteritems() %}
+{%- if key.startswith('pki_') %}
+{{ key }} = {{ value }}
+{%- endif %}
+{%- endfor %}
+{%- endfor %}
diff --git a/dogtag/init.sls b/dogtag/init.sls
new file mode 100644
index 0000000..68f3c64
--- /dev/null
+++ b/dogtag/init.sls
@@ -0,0 +1,9 @@
+{%- if pillar.dogtag is defined %}
+include:
+{%- if pillar.dogtag.server is defined %}
+- dogtag.server
+{%- endif %}
+{%- if pillar.dogtag.client is defined %}
+- dogtag.client
+{%- endif %}
+{%- endif %}
diff --git a/dogtag/map.jinja b/dogtag/map.jinja
new file mode 100644
index 0000000..cab5c5b
--- /dev/null
+++ b/dogtag/map.jinja
@@ -0,0 +1,30 @@
+{%- load_yaml as server_defaults %}
+default:
+  default_config_options:
+    pki_admin_password: PASSWORD
+    pki_backup_password: PASSWORD
+    pki_client_database_password: PASSWORD
+    pki_client_pkcs12_password: PASSWORD
+    pki_clone_pkcs12_password: PASSWORD
+    pki_ds_password: PASSWORD
+    pki_token_password: PASSWORD
+    pki_security_domain_name: EXAMPLE
+    pki_security_domain_password: PASSWORD
+  subsystems:
+    KRA:
+      pkgs: [pki-ca, pki-kra]
+    OCSP:
+      pkgs: [pki-ca, pki-ocsp]
+    TKS:
+      pkgs: [pki-tks]
+    TPS:
+      pkgs: [pki-tps, pki-tps-client]
+      pki_authdb_basedn: 'o=pki-tomcat-TPS'
+Debian:
+  pkgs:
+  - python-nss
+  - 389-ds-base
+  - pki-ca
+{%- endload %}
+
+{%- set server = salt['grains.filter_by'](server_defaults, merge=salt['pillar.get']('dogtag:server'), base='default') %}
diff --git a/dogtag/server.sls b/dogtag/server.sls
new file mode 100644
index 0000000..a55c39b
--- /dev/null
+++ b/dogtag/server.sls
@@ -0,0 +1,73 @@
+{%- from "dogtag/map.jinja" import server with context %}
+{%- if server.enabled %}
+
+dogtag_server_packages:
+  pkg.installed:
+  - names: {{ server.pkgs }}
+
+/etc/dogtag:
+  file.directory:
+  - makedirs: True
+  - user: pkiuser
+  - group: pkiuser
+  - mode: 600
+  - require:
+    - pkg: dogtag_server_packages
+
+/etc/dogtag/389-ds_setup.inf:
+  file.managed:
+  - source: salt://dogtag/files/389-ds_setup.inf
+  - template: jinja
+  - require:
+    - pkg: dogtag_server_packages
+
+setup-ds --silent --file=/etc/dogtag/389-ds_setup.inf:
+  cmd.run:
+  {%- if grains.get('noservices') %}
+  - onlyif: /bin/false
+  {%- endif %}
+  - require:
+    - file: /etc/dogtag/389-ds_setup.inf
+  - unless: ldapwhoami -x -p {{ server.ldap_server_port|default(389) }} -h {{ server.ldap_hostname|default('localhost') }} -w {{ server.ldap_dn_password|default('PASSWORD') }} -D '{{ server.ldap_dn|default('cn=Directory Manager') }}'
+
+
+/etc/dogtag/dogtag.cfg:
+  file.managed:
+  - source: salt://dogtag/files/dogtag.cfg
+  - template: jinja
+  - require:
+     - pkg: dogtag_server_packages
+
+{# Need to use exact order of subsystems #}
+{%- for key_name in ('CA', 'KRA', 'OCSP', 'TKS', 'TPS') %}
+{%- set key=server.subsystems.get(key_name, False) %}
+{%- if key and key.get('enabled', False) %}
+
+{%- if key and key.get('pkgs', False) %}
+dogtag_{{ key_name }}_subsystem_packages:
+  pkg.installed:
+  - names: {{ key.pkgs }}
+{%- endif %}
+
+pkispawn -f /etc/dogtag/dogtag.cfg -s {{ key_name }}:
+  cmd.run:
+  {%- if grains.get('noservices') %}
+  - onlyif: /bin/false
+  {%- endif %}
+  - unless: pki-server subsystem-show {{ key_name|lower }}
+
+{%- endif %}
+{%- endfor %}
+
+
+{%- if server.get('export_pem_file_path', False) %}
+openssl pkcs12 -in /root/.dogtag/pki-tomcat/ca_admin_cert.p12 -passin pass:{{ server.default_config_options.pki_client_pkcs12_password|default('PASSWORD') }} -out {{ server.export_pem_file_path }} -nodes:
+  cmd.run:
+  {%- if grains.get('noservices') %}
+  - onlyif: /bin/false
+  {%- endif %}
+  - require:
+    - file: /etc/dogtag/dogtag.cfg
+{%- endif %}
+
+{%- endif %}
diff --git a/metadata.yml b/metadata.yml
new file mode 100644
index 0000000..72db09f
--- /dev/null
+++ b/metadata.yml
@@ -0,0 +1,3 @@
+name: "dogtag"
+version: "0.1"
+source: "https://github.com/salt-formulas/salt-formula-dogtag"
diff --git a/metadata/service/server/single.yml b/metadata/service/server/single.yml
new file mode 100644
index 0000000..3e99d0d
--- /dev/null
+++ b/metadata/service/server/single.yml
@@ -0,0 +1,17 @@
+applications:
+- dogtag
+parameters:
+  dogtag:
+    server:
+      enabled: True
+      subsystems:
+        CA:
+          enabled: True
+        KRA:
+          enabled: True
+        OCSP:
+          enabled: True
+        TKS:
+          enabled: True
+        TPS:
+          enabled: True
diff --git a/tests/pillar/dogtag_single.sls b/tests/pillar/dogtag_single.sls
new file mode 100644
index 0000000..3508192
--- /dev/null
+++ b/tests/pillar/dogtag_single.sls
@@ -0,0 +1,15 @@
+dogtag:
+  server:
+    enabled: True
+    export_pem_file_path: /etc/barbican/kra_admin_cert.pem
+    subsystems:
+      CA:
+        enabled: True
+      KRA:
+        enabled: True
+      OCSP:
+        enabled: True
+      TKS:
+        enabled: True
+      TPS:
+        enabled: True
diff --git a/tests/run_tests.sh b/tests/run_tests.sh
new file mode 100755
index 0000000..3f42101
--- /dev/null
+++ b/tests/run_tests.sh
@@ -0,0 +1,162 @@
+#!/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}"
+
+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
+
+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