---
# {{ project_name }} - Ansible Deployment Playbook
# Generated by typedialog-prov-gen

- name: Deploy {{ project_name }}
  hosts: app_servers
  become: yes
  vars:
    project_name: "{{ project_name }}"
    deploy_user: "{{ deploy_user | default(value="deploy") }}"
    app_dir: "/opt/{{ project_name }}"

  tasks:
    - name: Update apt cache
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Install system dependencies
      apt:
        name:
          - curl
          - wget
          - git
          - build-essential
{% if infrastructure.database.db_type == "postgres" %}
          - postgresql-client
{% elif infrastructure.database.db_type == "mysql" %}
          - mysql-client
{% endif %}
        state: present

    - name: Create deployment user
      user:
        name: "{{"{{ deploy_user }}"}}"
        shell: /bin/bash
        createhome: yes
        state: present

    - name: Create application directory
      file:
        path: "{{"{{ app_dir }}"}}"
        state: directory
        owner: "{{"{{ deploy_user }}"}}"
        group: "{{"{{ deploy_user }}"}}"
        mode: '0755'

{% if infrastructure.database %}
    - name: Configure database
      include_tasks: tasks/database.yml
{% endif %}

    - name: Deploy application
      git:
        repo: "{{ repository_url | default(value="https://github.com/youruser/" ~ project_name) }}"
        dest: "{{"{{ app_dir }}"}}"
        version: "{{ git_branch | default(value="main") }}"
      become_user: "{{"{{ deploy_user }}"}}"

    - name: Install application dependencies
      shell: |
        cd {{ app_dir }}
        cargo build --release
      become_user: "{{"{{ deploy_user }}"}}"

    - name: Install systemd service
      template:
        src: templates/{{ project_name }}.service.j2
        dest: /etc/systemd/system/{{ project_name }}.service
        mode: '0644'
      notify: Reload systemd

    - name: Enable and start service
      systemd:
        name: "{{ project_name }}"
        enabled: yes
        state: started

{% if infrastructure.monitoring contains "prometheus" %}
    - name: Install Prometheus node exporter
      include_tasks: tasks/prometheus-exporter.yml
{% endif %}

  handlers:
    - name: Reload systemd
      systemd:
        daemon_reload: yes

- name: Verify deployment
  hosts: app_servers
  tasks:
    - name: Check service status
      systemd:
        name: "{{ project_name }}"
      register: service_status

    - name: Display service status
      debug:
        msg: "Service {{ project_name }} is {{"{{ service_status.status.ActiveState }}"}}"
