- name: "Installing Nginx"
  apt:
    name: nginx
    state: latest
    update_cache: yes
  notify: "Restart nginx"

- name: "Install letsencrypt"
  apt:
    name: letsencrypt
    state: latest

- name: "Remove default nginx config"
  file:
    name: /etc/nginx/sites-enabled/default
    state: absent

- name: "Configure nginx Non SSL"
  template:
    src: nginx.conf.j2
    dest:  /etc/nginx/sites-enabled/default.conf
    owner: root
    mode: 0600
  notify: "Restart nginx"

- name: "Creating letsencrypt certificate"
  shell: letsencrypt certonly -n --webroot -w /var/www/html -m {{ letsencrypt_email }} --agree-tos -d {{ nginx_domain_name }}
  args:
    creates: /etc/letsencrypt/live/{{ nginx_domain_name }}

- name: "Generate dhparams NOTE: This will take a long time to complete "
  shell: openssl dhparam -out /etc/nginx/dhparams.pem 2048
  args:
    creates: /etc/nginx/dhparams.pem

- name: "Configure nginx SSL"
  template:
    src: nginxssl.conf.j2
    dest:  /etc/nginx/sites-enabled/default_ssl.conf
    owner: root
    mode: 0600
  notify: "Restart nginx"

- name: "Add letsencrypt cronjob for cert renewal"
  cron:
    name: letsencrypt_renewal
    special_time: monthly
    job: letsencrypt --renew certonly -n --webroot -w /var/www/html -m {{ letsencrypt_email }} --agree-tos -d {{ nginx_domain_name }} && service nginx reload
