- hosts: "{{ variable_host }}"
  become: yes
  become_method: sudo
  gather_facts: no
  tasks:

    - name: Check if .git exists
      stat:
        path: "{{ CONFIG_DIR }}/.git"
      register: register_name

    - name: Fail if has been installed
      fail:
        msg="Git configuration not found. Initialize git at the beginning"
      when: not register_name.stat.exists and INIT == '0' and DELJOB == '0'

    - name: Install git
      package:
        name: git
        state: present
      environment:
        http_proxy: "{{PROXY}}"
        https_proxy: "{{PROXY}}"
      when: INIT == '1'

    - name: Create home dir
      file:
        path: '/home/{{ ansible_user }}/.ssh'
        state: directory
        mode: 0700
        group: '{{ ansible_user }}'
        owner: '{{ ansible_user }}'
      when: INIT == '1'

    - name: Copy ssh file
      copy:
        src: '{{ KEY }}'
        dest: '/home/{{ ansible_user }}/.ssh/id_rsa'
        mode: 0600
        group: '{{ ansible_user }}'
        owner: '{{ ansible_user }}'
        force: no
      when: INIT == '1'

    - name: Add write permisions
      shell: "chmod o+wr -R {{ CONFIG_DIR }}"

    - name: Git init
      shell: 'cd {{ CONFIG_DIR }} && git init'
      when: INIT == '1'
      become: no

    - name: Git configure
      blockinfile:
        path: "{{ CONFIG_DIR }}/.git/config"
        block: |
          [user]
          	name = Roxy-WI
          	email = roxy-wi@.com
      when: INIT == '1'

    - name: Git add remote
      shell: 'cd {{ CONFIG_DIR }} && git add --all . && git commit -m "Roxy-WI init repo" && git branch -M {{ BRANCH }} && git remote add origin {{ REPO }}'
      when: INIT == '1'
      become: no

    - name: Git add push
      shell: 'cd {{ CONFIG_DIR }} && GIT_SSH_COMMAND="ssh -o StrictHostKeyChecking=no" git push -u origin {{ BRANCH }}'
      when: INIT == '1'
      become: no

    - name: Creates git job
      cron:
        name: "Git backup {{ SERVICE }} configs"
        special_time: "{{ PERIOD }}"
        job: 'cd {{ CONFIG_DIR }} && git add --all . && git commit -m "Roxy-WI backup job at $(date)" && git push --set-upstream origin {{ BRANCH }}'
      when: DELJOB == '0'
      become: no

    - name: Removes git backup job
      cron:
        name: "Git backup {{ SERVICE }} configs"
        state: absent
      when: DELJOB == '1'
      become: no
