---
- name: Deploy Undatable.me Application
  hosts: web_servers
  become: yes
  vars:
    app_name: undatable
    app_path: /var/www/html/undatable
    db_host: "{{ hostvars['localhost']['db_endpoint'] }}"
    db_name: undatable_me
    db_user: "{{ db_username }}"
    db_password: "{{ db_password }}"
    s3_bucket: "{{ hostvars['localhost']['s3_bucket'] }}"
    aws_region: "{{ aws_region | default('us-east-1') }}"

  tasks:
    - name: Wait for system to be ready
      wait_for_connection:
        timeout: 300

    - name: Update system packages
      yum:
        name: "*"
        state: latest
        update_cache: yes

    - name: Install required packages
      yum:
        name:
          - httpd
          - php
          - php-mysqlnd
          - php-json
          - php-curl
          - php-mbstring
          - php-xml
          - php-zip
          - php-gd
          - git
          - unzip
          - mysql
        state: present

    - name: Install Composer
      shell: |
        curl -sS https://getcomposer.org/installer | php
        mv composer.phar /usr/local/bin/composer
        chmod +x /usr/local/bin/composer
      args:
        creates: /usr/local/bin/composer

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

    - name: Create uploads directory
      file:
        path: "{{ app_path }}/uploads"
        state: directory
        owner: apache
        group: apache
        mode: '0755'

    - name: Create config directory
      file:
        path: "{{ app_path }}/config"
        state: directory
        owner: apache
        group: apache
        mode: '0755'

    - name: Copy application files
      synchronize:
        src: "{{ playbook_dir }}/../"
        dest: "{{ app_path }}/"
        delete: yes
        rsync_opts:
          - "--exclude=terraform/"
          - "--exclude=ansible/"
          - "--exclude=.git/"
          - "--exclude=vendor/"
          - "--exclude=*.log"
          - "--exclude=config.json"

    - name: Set application file permissions
      file:
        path: "{{ app_path }}"
        owner: apache
        group: apache
        recurse: yes

    - name: Set executable permissions on PHP files
      file:
        path: "{{ app_path }}"
        mode: '0644'
        recurse: yes
        state: file

    - name: Set directory permissions
      shell: find {{ app_path }} -type d -exec chmod 755 {} \;

    - name: Install Composer dependencies
      composer:
        command: install
        working_dir: "{{ app_path }}"
        no_dev: yes
        optimize_autoloader: yes
      become_user: apache

    - name: Create database configuration
      template:
        src: database.php.j2
        dest: "{{ app_path }}/config/database.php"
        owner: apache
        group: apache
        mode: '0644'

    - name: Create application configuration
      template:
        src: config.json.j2
        dest: "{{ app_path }}/config.json"
        owner: apache
        group: apache
        mode: '0644'

    - name: Configure Apache virtual host
      template:
        src: undatable.conf.j2
        dest: /etc/httpd/conf.d/undatable.conf
        backup: yes
      notify: restart apache

    - name: Create .htaccess file
      template:
        src: htaccess.j2
        dest: "{{ app_path }}/.htaccess"
        owner: apache
        group: apache
        mode: '0644'

    - name: Configure PHP settings
      lineinfile:
        path: /etc/php.ini
        regexp: "{{ item.regexp }}"
        line: "{{ item.line }}"
        backup: yes
      loop:
        - { regexp: '^upload_max_filesize', line: 'upload_max_filesize = 50M' }
        - { regexp: '^post_max_size', line: 'post_max_size = 50M' }
        - { regexp: '^max_execution_time', line: 'max_execution_time = 300' }
        - { regexp: '^memory_limit', line: 'memory_limit = 256M' }
        - { regexp: '^max_input_vars', line: 'max_input_vars = 3000' }
      notify: restart apache

    - name: Start and enable Apache
      systemd:
        name: httpd
        state: started
        enabled: yes

    - name: Wait for database to be ready
      wait_for:
        host: "{{ db_host.split(':')[0] }}"
        port: 3306
        timeout: 300

    - name: Initialize database schema
      mysql_db:
        login_host: "{{ db_host.split(':')[0] }}"
        login_user: "{{ db_user }}"
        login_password: "{{ db_password }}"
        name: "{{ db_name }}"
        state: present

    - name: Import main database schema
      mysql_db:
        login_host: "{{ db_host.split(':')[0] }}"
        login_user: "{{ db_user }}"
        login_password: "{{ db_password }}"
        name: "{{ db_name }}"
        state: import
        target: "{{ app_path }}/messaging_schema.sql"
      ignore_errors: yes

    - name: Create database initialization script
      template:
        src: init_db.php.j2
        dest: "{{ app_path }}/init_db.php"
        owner: apache
        group: apache
        mode: '0644'

    - name: Run database initialization
      command: php {{ app_path }}/init_db.php
      become_user: apache
      register: db_init_result
      failed_when: db_init_result.rc != 0 and 'already exists' not in db_init_result.stderr

    - name: Remove database initialization script
      file:
        path: "{{ app_path }}/init_db.php"
        state: absent

    - name: Create health check endpoint
      template:
        src: health.php.j2
        dest: "{{ app_path }}/health.php"
        owner: apache
        group: apache
        mode: '0644'

    - name: Install AWS CLI
      shell: |
        curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
        unzip awscliv2.zip
        ./aws/install
        rm -rf awscliv2.zip aws/
      args:
        creates: /usr/local/bin/aws

    - name: Configure log rotation
      template:
        src: logrotate.j2
        dest: /etc/logrotate.d/undatable
        mode: '0644'

    - name: Create systemd service for background tasks
      template:
        src: undatable-worker.service.j2
        dest: /etc/systemd/system/undatable-worker.service
        mode: '0644'
      notify:
        - reload systemd
        - restart undatable-worker

    - name: Install and configure CloudWatch agent
      block:
        - name: Install CloudWatch agent
          yum:
            name: amazon-cloudwatch-agent
            state: present

        - name: Configure CloudWatch agent
          template:
            src: cloudwatch-config.json.j2
            dest: /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json
            mode: '0644'

        - name: Start CloudWatch agent
          shell: |
            /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
            -a fetch-config -m ec2 \
            -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.json -s

    - name: Configure firewall
      firewalld:
        service: "{{ item }}"
        permanent: yes
        state: enabled
        immediate: yes
      loop:
        - http
        - https
      ignore_errors: yes

    - name: Create backup script
      template:
        src: backup.sh.j2
        dest: /usr/local/bin/undatable-backup.sh
        mode: '0755'

    - name: Schedule daily backups
      cron:
        name: "Undatable.me daily backup"
        minute: "0"
        hour: "2"
        job: "/usr/local/bin/undatable-backup.sh"

    - name: Final permission fix
      shell: |
        chown -R apache:apache {{ app_path }}
        find {{ app_path }} -type f -exec chmod 644 {} \;
        find {{ app_path }} -type d -exec chmod 755 {} \;
        chmod 755 {{ app_path }}/uploads

  handlers:
    - name: restart apache
      systemd:
        name: httpd
        state: restarted

    - name: reload systemd
      systemd:
        daemon_reload: yes

    - name: restart undatable-worker
      systemd:
        name: undatable-worker
        state: restarted
        enabled: yes
