git_pkg:
  pkg.installed:
    - name: git

{##ensure that git pillar exists##}
{%- if pillar['git'] is defined -%}

  {##set up git repos for this server##}
  {%- for repo in pillar['git'] %}

  {%- if pillar['git'][repo]['key'] is defined %}
{{ repo }}_key:
  file.managed:
    - name: /root/.ssh/{{ pillar['git'][repo]['key'] }}
    - source: salt://secure/keys/git/{{ pillar['git'][repo]['key'] }}
    - user: root
    - group: root
    - mode: 600
    - makedirs: true
  {% endif %}
{{ repo }}:
  git.latest:
    - name: {{ pillar['git'][repo]['repo'] }}
    - target: {{ pillar['git'][repo]['path'] }}
    {%- if pillar['git'][repo]['branch'] is defined %}
    - branch: {{ pillar['git'][repo]['branch'] }}
    - rev: {{ pillar['git'][repo]['branch'] }}
    {%- endif -%}
    {%- if pillar['git'][repo]['key'] is defined %}
    - identity: /root/.ssh/{{ pillar['git'][repo]['key'] }}
    {%- endif -%}
    {%- if pillar['git'][repo]['force'] is defined %}
    - force_fetch: {{ pillar['git'][repo]['force'] }}
    - force_checkout: {{ pillar['git'][repo]['force'] }}
    - force_reset: {{ pillar['git'][repo]['force'] }}
    - force_clone: {{ pillar['git'][repo]['force'] }}
    {%- endif -%}

    {##ensure that name is defined pillar exists##}
    {%- if pillar['git'][repo]['name'] is defined %}
{{ repo }}_name:
  git.config_set:
    - name: user.name
    - value: {{ pillar['git'][repo]['name'] }}
    - repo: {{ pillar['git'][repo]['path'] }}
    {%- endif -%}

    {##ensure that email is defined pillar exists##}
    {%- if pillar['git'][repo]['email'] is defined %}
{{ repo }}_email:
  git.config_set:
    - name: user.email
    - value: {{ pillar['git'][repo]['email'] }}
    - repo: {{ pillar['git'][repo]['path'] }}
    {%- endif -%}

    {##ensure that key is defined pillar exists##}
    {%- if pillar['git'][repo]['key'] is defined %}
{{ repo }}_conf_key:
  git.config_set:
    - name: core.sshCommand
    - value: "ssh -i /root/.ssh/{{ pillar['git'][repo]['key'] }}"
    - repo: {{ pillar['git'][repo]['path'] }}
    {%- endif -%}
  {%- endfor %}
{%- endif %}