---
- name: Bootstrap VPS
  become: true
  vars:
    ansible_ssh_user: root

  block:
    - name: Wait up to 600 seconds for target connection to become reachable/usable
      wait_for_connection:

    - name: Create ansible user
      user:
        name: ansible
        groups: sudo

    - name: Create ansible user ssh directory
      file:
        path: /home/ansible/.ssh
        state: directory
        owner: ansible
        group: ansible
        mode: 0700

    - name: Copy authorized_keys
      copy:
        src: /root/.ssh/authorized_keys
        dest: /home/ansible/.ssh/authorized_keys
        owner: ansible
        group: ansible
        mode: 0600
        remote_src: true

    # - name: Allow passwordless sudo commands
    #   community.general.sudoers:
    #     name: ansible-passwordless-sudo
    #     state: present
    #     user: ansible
    #     commands: ALL
    #     nopassword: true

    ## TODO: Limit to account 'ansible'.
    - name: Allow sudo group to use sudo without password
      ansible.builtin.lineinfile:
        dest: /etc/sudoers.d/user-passwordless-ansible
        state: present
        create: yes
        line: '%sudo ALL=(ALL:ALL) NOPASSWD:ALL'
        validate: '/usr/sbin/visudo -cf %s'
        mode: '0440'

    - name: Add host to hosts file
      lineinfile:
        path: /etc/hosts
        search_string: '127.0.0.1'
        line: '127.0.0.1 localhost host'
        owner: root
        group: root
        mode: '0644'
