Initial commit

Change-Id: Ife61c7bdd6b1894c460f835f77746793de13e544
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..3b118ea
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,14 @@
+  Copyright (c) 2017 Mirantis et al.
+
+  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..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/README.rst b/README.rst
new file mode 100644
index 0000000..30a6f38
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,63 @@
+=======================
+Salt Telegraf formula
+=======================
+
+Power your metrics and alerting with a leading open-source monitoring
+solution.
+
+Sample pillars
+==============
+
+.. code-block:: yaml
+
+  telegraf:
+    agent:
+      enabled: true
+      interval: 15
+      round_interval: false
+      metric_batch_size: 1000
+      metric_buffer_limit: 10000
+      collection_jitter: 2
+      output:
+        prometheus_client:
+          bind:
+            address: 0.0.0.0
+            port: 9126
+          engine: prometheus
+      input:
+        diskio:
+        processes:
+        net:
+
+Documentation and Bugs
+======================
+
+To learn how to install and update salt-formulas, consult the documentation
+available online at:
+
+    http://salt-formulas.readthedocs.io/
+
+In the unfortunate event that bugs are discovered, they should be reported to
+the appropriate issue tracker. Use Github issue tracker for specific salt
+formula:
+
+    https://github.com/salt-formulas/salt-formula-logrotate/issues
+
+For feature requests, bug reports or blueprints affecting entire ecosystem,
+use Launchpad salt-formulas project:
+
+    https://launchpad.net/salt-formulas
+
+You can also join salt-formulas-users team and subscribe to mailing list:
+
+    https://launchpad.net/~salt-formulas-users
+
+Developers wishing to work on the salt-formulas projects should always base
+their work on master branch and submit pull request against specific formula.
+
+    https://github.com/salt-formulas/salt-formula-logrotate
+
+Any questions or feedback is always welcome so feel free to join our IRC
+channel:
+
+    #salt-formulas @ irc.freenode.net
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..34c70f1
--- /dev/null
+++ b/debian/changelog
@@ -0,0 +1,5 @@
+salt-formula-telegraf (0.1) trusty; urgency=medium
+
+  * Initial release
+
+ -- Bartosz Kupidura <bkupidura@mirantis.com>  Fri, 10 Mar 2017 09:14:06 +0100
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..692bd18
--- /dev/null
+++ b/debian/control
@@ -0,0 +1,15 @@
+Source: salt-formula-telegraf
+Maintainer: Salt Formulas Community <salt-formulas@freelists.org>
+Section: admin
+Priority: optional
+Build-Depends: salt-master, python, python-yaml, debhelper (>= 9)
+Standards-Version: 3.9.6
+Homepage: https://github.com/salt-formulas/salt-formulas
+Vcs-Browser: https://github.com/salt-formulas/salt-formula-telegraf
+Vcs-Git: https://github.com/salt-formulas/salt-formula-telegraf.git
+
+Package: salt-formula-telegraf
+Architecture: all
+Depends: ${misc:Depends}, salt-master, reclass
+Description: telegraf Salt formula
+ Install and configure telegraf monitoring
diff --git a/debian/copyright b/debian/copyright
new file mode 100644
index 0000000..8e0f18e
--- /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-telegraf
+Upstream-Contact: Salt Formulas Community <salt-formulas@freelists.org>
+Source: https://github.com/salt-formulas/salt-formula-telegraf
+
+Files: *
+Copyright: 2017 Mirantis et al.
+License: Apache-2.0
+  Copyright (C) 2017 Mirantis et al.
+  .
+  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..a1320b1
--- /dev/null
+++ b/debian/docs
@@ -0,0 +1 @@
+README.rst
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/metadata.yml b/metadata.yml
new file mode 100644
index 0000000..1f0a46c
--- /dev/null
+++ b/metadata.yml
@@ -0,0 +1,3 @@
+name: "telegraf"
+version: "0.1"
+source: "https://github.com/salt-formulas/salt-formula-telegraf"
diff --git a/metadata/service/agent.yml b/metadata/service/agent.yml
new file mode 100644
index 0000000..5c6c2f6
--- /dev/null
+++ b/metadata/service/agent.yml
@@ -0,0 +1,11 @@
+applications:
+  - telegraf
+parameters:
+  telegraf:
+    agent:
+      enabled: true
+      interval: 15
+      round_interval: false
+      metric_batch_size: 1000
+      metric_buffer_limit: 10000
+      collection_jitter: 2
diff --git a/metadata/service/agent/output/prometheus_client.yml b/metadata/service/agent/output/prometheus_client.yml
new file mode 100644
index 0000000..5537b75
--- /dev/null
+++ b/metadata/service/agent/output/prometheus_client.yml
@@ -0,0 +1,9 @@
+parameters:
+  telegraf:
+    agent:
+      output:
+        prometheus_client:
+          bind:
+            address: 0.0.0.0
+            port: 9126
+          engine: prometheus
diff --git a/telegraf/agent.sls b/telegraf/agent.sls
new file mode 100644
index 0000000..f272fd3
--- /dev/null
+++ b/telegraf/agent.sls
@@ -0,0 +1,84 @@
+{% from "telegraf/map.jinja" import agent with context %}
+{%- if agent.enabled %}
+
+telegraf_packages:
+  pkg.installed:
+    - names: {{ agent.pkgs }}
+
+telegraf_config:
+  file.managed:
+    - name: {{ agent.file.config }}
+    - source: salt://telegraf/files/telegraf.conf
+    - user: root
+    - group: root
+    - mode: 644
+    - template: jinja
+    - require:
+      - pkg: telegraf_packages
+
+{%- for name,values in agent.input.iteritems() %}
+
+input_{{ name }}:
+  file.managed:
+    - name: {{ agent.dir.config }}/input-{{ name }}.conf
+    - source: salt://telegraf/files/input/{{ name }}.conf
+    - user: root
+    - group: root
+    - mode: 644
+    - template: jinja
+    - require:
+      - pkg: telegraf_packages
+    - watch_in:
+      - service: telegraf_service
+    - defaults:
+        name: {{ name }}
+        values: {{ values }}
+
+{%- endfor %}
+
+{%- for name,values in agent.output.iteritems() %}
+
+output_{{ name }}:
+  file.managed:
+    - name: {{ agent.dir.config }}/output-{{ name }}.conf
+    - source: salt://telegraf/files/output/{{ name }}.conf
+    - user: root
+    - group: root
+    - mode: 644
+    - template: jinja
+    - require:
+      - pkg: telegraf_packages
+    - watch_in:
+      - service: telegraf_service
+    - defaults:
+        name: {{ name }}
+        values: {{ values }}
+
+{%- if name == 'prometheus_client' %}
+
+{%- if values.bind.address == '0.0.0.0' %}
+{%- set address = grains['fqdn_ip4'][0] %}
+{%- else %}
+{%- set address = values.bind.address %}
+{%- endif %}
+
+prometheus_client_grain:
+  grains.present:
+    - name: prometheus_client
+    - force: True
+    - value:
+        address: {{ address }}
+        port: {{ values.bind.port }}
+
+{%- endif %}
+
+{%- endfor %}
+
+telegraf_service:
+  service.running:
+    - name: telegraf
+    - enable: True
+    - watch:
+      - file: telegraf_config
+
+{%- endif %}
diff --git a/telegraf/files/input/cpu.conf b/telegraf/files/input/cpu.conf
new file mode 100644
index 0000000..ffc92ec
--- /dev/null
+++ b/telegraf/files/input/cpu.conf
@@ -0,0 +1,9 @@
+[[inputs.{{ name }}]]
+{%- if values is defined %}
+{%- if values.totalcpu is defined %}
+totalcpu = {{ values.totalcpu | lower }}
+{%- endif %}
+{%- if values.percpu is defined %}
+percpu = {{ values.percpu | lower }}
+{%- endif %}
+{%- endif %}
diff --git a/telegraf/files/input/disk.conf b/telegraf/files/input/disk.conf
new file mode 100644
index 0000000..9dd9e67
--- /dev/null
+++ b/telegraf/files/input/disk.conf
@@ -0,0 +1,6 @@
+[[inputs.{{ name }}]]
+{%- if values is defined %}
+{%- if values.mount_points is defined%}
+mount_points = {{ values.mount_points }}
+{%- endif %}
+{%- endif %}
diff --git a/telegraf/files/input/diskio.conf b/telegraf/files/input/diskio.conf
new file mode 100644
index 0000000..01bf009
--- /dev/null
+++ b/telegraf/files/input/diskio.conf
@@ -0,0 +1,9 @@
+[[inputs.{{ name }}]]
+{%- if values is defined %}
+{%- if values.devices is defined %}
+devices = {{ values.devices }}
+{%- endif %}
+{%- if values.skip_serial_number is defined %}
+skip_serial_number = {{ values.skip_serial_number | lower }}
+{%- endif %}
+{%- endif %}
diff --git a/telegraf/files/input/mem.conf b/telegraf/files/input/mem.conf
new file mode 100644
index 0000000..b505dfc
--- /dev/null
+++ b/telegraf/files/input/mem.conf
@@ -0,0 +1 @@
+[[inputs.{{ name }}]]
diff --git a/telegraf/files/input/net.conf b/telegraf/files/input/net.conf
new file mode 100644
index 0000000..b505dfc
--- /dev/null
+++ b/telegraf/files/input/net.conf
@@ -0,0 +1 @@
+[[inputs.{{ name }}]]
diff --git a/telegraf/files/input/netstat.conf b/telegraf/files/input/netstat.conf
new file mode 100644
index 0000000..b505dfc
--- /dev/null
+++ b/telegraf/files/input/netstat.conf
@@ -0,0 +1 @@
+[[inputs.{{ name }}]]
diff --git a/telegraf/files/input/processes.conf b/telegraf/files/input/processes.conf
new file mode 100644
index 0000000..b505dfc
--- /dev/null
+++ b/telegraf/files/input/processes.conf
@@ -0,0 +1 @@
+[[inputs.{{ name }}]]
diff --git a/telegraf/files/input/system.conf b/telegraf/files/input/system.conf
new file mode 100644
index 0000000..b505dfc
--- /dev/null
+++ b/telegraf/files/input/system.conf
@@ -0,0 +1 @@
+[[inputs.{{ name }}]]
diff --git a/telegraf/files/output/prometheus_client.conf b/telegraf/files/output/prometheus_client.conf
new file mode 100644
index 0000000..6677bc2
--- /dev/null
+++ b/telegraf/files/output/prometheus_client.conf
@@ -0,0 +1,4 @@
+[[outputs.{{ name }}]]
+{%- if values is defined %}
+listen = "{{ values.bind.address }}:{{ values.bind.port }}"
+{%- endif %}
diff --git a/telegraf/files/telegraf.conf b/telegraf/files/telegraf.conf
new file mode 100644
index 0000000..941a86c
--- /dev/null
+++ b/telegraf/files/telegraf.conf
@@ -0,0 +1,10 @@
+{%- from "telegraf/map.jinja" import agent with context -%}
+
+[agent]
+  interval = "{{ agent.interval }}s"
+  round_interval = {{ agent.round_interval | lower }}
+  metric_batch_size = {{ agent.metric_batch_size }}
+  metric_buffer_limit = {{ agent.metric_buffer_limit }}
+  collection_jitter = "{{ agent.collection_jitter }}s"
+  hostname = ""
+  omit_hostname = false
diff --git a/telegraf/init.sls b/telegraf/init.sls
new file mode 100644
index 0000000..97bf655
--- /dev/null
+++ b/telegraf/init.sls
@@ -0,0 +1,2 @@
+include:
+  - telegraf.agent
diff --git a/telegraf/map.jinja b/telegraf/map.jinja
new file mode 100644
index 0000000..9dd1bed
--- /dev/null
+++ b/telegraf/map.jinja
@@ -0,0 +1,25 @@
+{% set agent = salt['grains.filter_by']({
+    'default': {
+        'input': {
+           'cpu': {
+             'percpu': 'true',
+             'totalcpu': 'true'
+           },
+           'disk': {
+             'ignore_fs': ['tmpfs', 'devtmpfs']
+           },
+           'mem': {},
+           'system': {},
+        },
+    },
+}, merge=salt['grains.filter_by']({
+    'Debian': {
+      'pkgs': ['telegraf'],
+      'file': {
+        'config': '/etc/telegraf/telegraf.conf'
+      },
+      'dir': {
+        'config': '/etc/telegraf/telegraf.d'
+      },
+    },
+}, merge=salt['pillar.get']('telegraf:agent'))) %}
diff --git a/tests/pillar/telegraf_agent.sls b/tests/pillar/telegraf_agent.sls
new file mode 100644
index 0000000..c19fdd2
--- /dev/null
+++ b/tests/pillar/telegraf_agent.sls
@@ -0,0 +1,18 @@
+telegraf:
+  agent:
+    enabled: true
+    interval: 15
+    round_interval: false
+    metric_batch_size: 1000
+    metric_buffer_limit: 10000
+    collection_jitter: 2
+    input:
+      disk:
+      processes:
+      mem:
+    output:
+      prometheus_client:
+        bind:
+          address: 127.0.0.1
+          port: 9126
+        engine: prometheus
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