---

- name: ensure backend-scripts-log-dir
  file: path=~/.cronlog state=directory mode=0700

# FIXME: maybe move behind next block?
- name: clone backend scripts
  git:
    dest: "~/clones/backend-scripts"
    repo: "https://github.com/freifunk-mwu/backend-scripts.git"
    accept_hostkey: yes

- block:  # replaces backend script bootstrap_git_all.py
  - name: generate host key
    command: ssh-keygen -t ed25519 -N "" -f {{ansible_hostname}}_rsa
    args:
      chdir: ~/.ssh
      creates: ~/.ssh/{{ansible_hostname}}_rsa
    register: keypair

  - name: generate ssh config entry
    blockinfile:
      block: |
          Host github_mwu
          User git
          Hostname github.com
          PreferredAuthentications publickey
          IdentityFile ~/.ssh/{{ansible_hostname}}_rsa
      create: yes
      dest: ~/.ssh/config
      marker: "# {mark} ANSIBLE MANAGED BLOCK github_mwu"
      mode: 0640

  - name: change git user name
    git_config:
      scope: global
      name: "user.name"
      value: "{{ansible_hostname}}"

  - name: change git user email
    git_config:
      scope: global
      name: "user.email"
      value: "{{ansible_hostname}}@{{ansible_fqdn}}"

  # block end

- block:
  - name: read new pubkey
    shell: cat ~/.ssh/{{ansible_hostname}}_rsa.pub
    register: ssh_pub_key

  - name: read existing github token from spinat
    shell: cat ~/.ssh/github-ansible-token
    register: github_access_token
    delegate_to: spinat.freifunk-mwu.de

  - name: register new pubkey with github freifunkmwu account
    github_key:
      name: "Server {{ansible_hostname}}"
      token: "{{github_access_token.stdout}}"
      pubkey: "{{ssh_pub_key.stdout}}"
      # FIXME: force yes ???
      force: no

  when: keypair.changed

- name: manage crontab - PATH
  cron: env=yes name=PATH value="/home/admin/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"

- name: manage crontab - entries
  cron: name={{mwu_m_item.n}} job={{mwu_m_item.j}} minute={{mwu_m_item.mi}}
        hour={{mwu_m_item.h}} day={{mwu_m_item.d}} month={{mwu_m_item.mo}}
        weekday={{mwu_m_item.w}}
  with_items:
  - { n: "sync_meshkeys", mi: "*/15", h: "*", d: "*", mo: "*", w: "*", j: "/usr/bin/python3 $HOME/clones/backend-scripts/sync_meshkeys_gw.py > $HOME/.cronlog/sync_meshkeys.log" }
    # FIXME: define hostvar for mi
  - { n: "snapshot_configs", mi: "23", h: "5,23", d: "*", mo: "*", w: "*", j: "/usr/bin/python3 $HOME/clones/backend-scripts/snapshot_configs_all.py > $HOME/.cronlog/snapshot_configs.log" }
  loop_control:
    loop_var: mwu_m_item