#
# Add users expected by tests. Assumes passwordless sudo to root.
#
# WARNING: this creates non-privilged accounts with pre-set passwords!
#
- name: Mitogen test users and groups
  hosts: all
  gather_facts: true
  strategy: mitogen_free
  become: true
  pre_tasks:
    - name: Disable non-localhost SSH for Mitogen users
      when: false
      blockinfile:
        path: /etc/ssh/sshd_config
        block: |
          Match User mitogen__* Address !127.0.0.1
            DenyUsers *

    - name: Create Mitogen test groups
      group:
        name: "{{ item.name }}"
      with_items: "{{ mitogen_test_groups }}"

    - name: Create user accounts
      vars:
        password: "{{ item.name | replace('mitogen__', '') }}_password"
      user:
        name: "{{ item.name }}"
        shell: /bin/bash
        groups: >-
          {{
            system_groups[ansible_system]
            + (item.groups | default(['mitogen__group']))
          }}
        password: >-
          {%- if ansible_system == 'Darwin' -%}
          {{ password }}
          {%- else -%}
          {{ password | password_hash('sha256') }}
          {%- endif -%}
        hidden: true  # Only has effect on macOS
      with_items: "{{ mitogen_test_users }}"

    - name: Readonly homedir for one account
      file:
        path: ~mitogen__readonly_homedir
        owner: root
        recurse: true
        state: directory

    - name: Slow bash profile for one account
      copy:
        dest: ~mitogen__slow_user/.{{item}}
        src: ../data/docker/mitogen__slow_user.profile
        owner: mitogen__slow_user
        group: mitogen__group
        mode: u=rw,go=r
      with_items:
      - bashrc
      - profile

    - name: "Login throws permission denied errors (issue #271)"
      copy:
        dest: ~mitogen__permdenied/.{{item}}
        src: ../data/docker/mitogen__permdenied.profile
        owner: mitogen__permdenied
        group: mitogen__group
        mode: u=rw,go=r
      with_items:
      - bashrc
      - profile

    - name: Install pubkey for mitogen__has_sudo_pubkey
      block:
        - file:
            path: ~mitogen__has_sudo_pubkey/.ssh
            state: directory
            mode: go=
            owner: mitogen__has_sudo_pubkey
            group: mitogen__group
        - copy:
            dest: ~mitogen__has_sudo_pubkey/.ssh/authorized_keys
            src: ../data/docker/mitogen__has_sudo_pubkey.key.pub
            mode: go=
            owner: mitogen__has_sudo_pubkey
            group: mitogen__group

  roles:
    - role: sudoers
