- name: Check if certs dir exists
  stat:
    path: "{{ OPENSSL_CERTS_PATH }}"
  register: certs_dir

- name: Check if server.pem file exists
  stat:
    path: "{{ OPENSSL_CERTS_PATH }}/server.pem"
  register: server_file

- name: "Create certs directory if not exists"
  file:
    path: "{{ OPENSSL_CERTS_PATH }}"
    state: directory
  when: not certs_dir.stat.exists

- name: Building your own CA
  shell: |
    openssl genrsa -des3 -passout pass:{{ USERNAME }} -out rootCA.key 2048  
    openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -passin pass:{{ USERNAME }} -out rootCA.pem \
    -subj "/C=US/ST=NY/L=NY/O=theorchard/OU=devorch/CN=*.{{ OPENSSL_CN }}/emailAddress={{ VHOST_SERVER_ADMIN }}"  
  args:
    chdir: "{{ OPENSSL_CERTS_PATH }}"
    executable: /bin/bash
  when: not certs_dir.stat.exists or not server_file.stat.exists

- name: Generate server.csr.cnf from template 
  template:
    src: "{{ playbook_dir }}/templates/openssl/server.csr.cnf.j2"
    dest: "{{ OPENSSL_CERTS_PATH }}/server.csr.cnf"
  delegate_to: localhost
  when: not certs_dir.stat.exists or not server_file.stat.exists

- name: Generating openssl private key
  shell: |
    openssl req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config <( cat server.csr.cnf )
  args:
    chdir: "{{ OPENSSL_CERTS_PATH }}"
    executable: /bin/bash
  when: not certs_dir.stat.exists or not server_file.stat.exists

- name: Generate v3.ext from template 
  template:
    src: "{{ playbook_dir }}/templates/openssl/v3.ext.j2"
    dest: "{{ OPENSSL_CERTS_PATH }}/v3.ext"
  delegate_to: localhost
  when: not certs_dir.stat.exists or not server_file.stat.exists

- name: Generating openssl required certs
  shell: |
    openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -passin pass:{{ USERNAME }} -CAcreateserial -out server.crt -days 300 -sha256 -extfile v3.ext
    cat server.key server.crt > server.pem
  args:
    chdir: "{{ OPENSSL_CERTS_PATH }}"
    executable: /bin/bash
  when: not certs_dir.stat.exists or not server_file.stat.exists
