---

# This playbook is designed to help when modifying the Windows script template
# in roles/vpn/templates/client_windows.ps1.j2
# It rebuilds the client_USER.ps1 scripts for each user defined in config.cfg,
# without redeploying users or opening an SSH connection to the Algo server at
# all.
#
# This playbook is _not_ part of a normal Algo deployment.
# It is only intended to speed up development of the client_USER.ps1 Windows
# Algo install scripts.
#
# REQUIREMENTS
# - Algo must have been deployed once
# - Windows users must have been enabled at deployment time
# - All users defined in config.cfg must not have changed
# - Only one Algo deployment exists in the configs/ directory
# - There must be exactly one subfolder in the configs/ directory:
#   the folder named after the IP of the algo server

- hosts: localhost
  gather_facts: False
  tags: always
  vars_files:
    - ../config.cfg

  tasks:

  - name: Get config subdir
    shell: find ../configs/* -maxdepth 0 -type d | sed 's/.*\///'
    register: config_subdir_result
  - fail:
      msg:
        - "Found wrong number of config subdirs... stdout:"
        - "{{ config_subdir_result.split('\n') }}"
    when: config_subdir_result.stdout.split('\n') | length != 1
  - set_fact:
      IP_subject_alt_name: "{{ config_subdir_result.stdout }}"
  - debug:
      var: IP_subject_alt_name

  - name: Register p12 PayloadContent
    shell: cat private/{{ item }}.p12 | base64
    register:  PayloadContent
    args:
      chdir: "../configs/{{ IP_subject_alt_name }}/pki/"
    with_items: "{{ users }}"

  - name: Set facts for mobileconfigs
    set_fact:
      proxy_enabled: false
      PayloadContentCA: "{{ lookup('file' , '../configs/{{ IP_subject_alt_name }}/pki/cacert.pem')|b64encode }}"

  - name: Build the windows client powershell script
    template:
      src: ../roles/vpn/templates/client_windows.ps1.j2
      dest: ../configs/{{ IP_subject_alt_name }}/windows_{{ item.0 }}.ps1
      mode: 0600
    with_together:
      - "{{ users }}"
      - "{{ PayloadContent.results }}"

  - name: List windows client powershell scripts
    debug:
      msg: "configs/{{ IP_subject_alt_name }}/windows_{{ item }}.ps1"
    with_items:
      - "{{ users }}"
