---
- name: golang | include vars
  include_vars: "{{ ansible_distribution | lower }}.yml"

- name: golang | Detecting golang architecture
  set_fact:
    golang_arch: "amd64"
  when: ansible_architecture == "x86_64"

- name: golang | Detecting golang architecture
  set_fact:
    golang_arch: "386"
  when: ansible_architecture != "x86_64"

- name: golang | Assume golang needs installation
  set_fact:
    install_golang: true

- name: golang | Get the golang bin file stat
  stat:
    path: /usr/local/bin/go
  register: golang_bin

- name: golang | Get the golang version (if golang is installed)
  block:
    - name: golang | Get the golang version
      shell: /usr/local/bin/go version
      register: cmd_output

    - name: golang | Do not require golang installation if already installed with the proper version
      set_fact:
        install_golang: false
      when: (cmd_output.stdout | trim) == ("go version go" ~ golang.version ~ " linux/" ~ golang_arch)
  when: golang_bin.stat.exists

- name: golang | Install golang {{ golang.version }}
  block:
    - name: golang | get go{{ golang.version }}.{{ansible_system | lower}}-{{golang_arch}}.tar.gz
      get_url:
        url: "https://dl.google.com/go/go{{ golang.version }}.{{ ansible_system | lower }}-{{ golang_arch }}.tar.gz"
        dest: "/tmp/go{{ golang.version }}.tar.gz"
        force_basic_auth: yes
        mode: 0755
        timeout: 30
      retries: 3

    - name: golang | Install golang
      unarchive:
        src: "/tmp/go{{ golang.version }}.tar.gz"
        dest: "/usr/local/"
        remote_src: yes

    - name: golang | Create symlink in /usr/local/bin
      file:
        state: link
        src: /usr/local/go/bin/go
        dest: /usr/local/bin/go
  when: install_golang
