---

- block:
  - name: install likewise (32-bit)
    apt:
      deb: https://artifactory.zooxlabs.com/artifactory/slurm/likewise-open_6.1.0.406-0ubuntu5.1_i386.deb
    when: ansible_machine == 'i686'

  - name: install likewise (64-bit)
    apt:
      deb: https://artifactory.zooxlabs.com/artifactory/slurm/likewise-open_6.1.0.406-0ubuntu5.1_amd64.deb
    when: ansible_machine == 'x86_64'

  - name: configure home directory template
    # TODO: We should write an ansible module that does idempotent operations.
    command: lwconfig HomeDirTemplate %H/%U
    # If the domain isn't set up yet, we'll get a cryptic error out of this:
    #   Problem executing '/usr/bin/lw-ad-cache --delete-all >/dev/null 2>/dev/null'
    #   Error: Error returned by external program
    # If we run that command ourselves, we can see the actual error:
    #   $ sudo /usr/bin/lw-ad-cache --delete-all
    #   Failed to empty cache.  Error code 40017 (LW_ERROR_NOT_HANDLED).
    #   The authentication request could not be handled
    # However, the config option *is* set correctly, as verified by 'lwconfig
    # --show HomeDirTemplate'.  So we can ignore this particular type of error.
    register: result
    failed_when: "result.rc != 0 and '/usr/bin/lw-ad-cache --delete-all' not in result.stderr"

  - name: don't make users add corp.zooxlabs.com to their usernames
    command: lwconfig AssumeDefaultDomain true
    register: result
    failed_when: "result.rc != 0 and '/usr/bin/lw-ad-cache --delete-all' not in result.stderr"

  - name: configure default shell template
    command: /usr/bin/lwregshell set_value [HKEY_THIS_MACHINE\\Services\\lsass\\Parameters\\Providers\\{{ item }}] LoginShellTemplate /bin/bash
    with_items:
      - ActiveDirectory
      - Local
  become: yes

- name: check domain status
  shell: lw-get-status corp.zooxlabs.com | grep -E '^\s+Status:' | awk '{print $2}'
  register: domain_status
  ignore_errors: true

  # This sometimes fails with "Error: LW_ERROR_NOT_HANDLED [code 0x00009c51]", but a retry
  # usually works.
- name: join machine to domain
  become: yes
  command: domainjoin-cli join --ou "ZOOX/Application Services/Servers/Pipedream" corp.zooxlabs.com svc-pd-ad-bind '{{ lookup('hashi_vault', 'secret=secret/ad/slurm_enroll_key').value }}'
  register: join_domain_result
  until: join_domain_result|success
  retries: 2
  when: domain_status.stdout != 'Online'
