- name: Configure automated backups
  hosts: yndx-client.practicumsuperstore.ru
  become: yes
  vars:
    backup_script: /home/backup-user/run-backup.sh
    backup_dir_local: /home/backup-user/backups
    remote_backup_dir: /home/anscfg/backups
  tasks:
    - name: Create local backup directory
      file:
        path: "{{ backup_dir_local }}"
        state: directory
        owner: backup-user
        group: backup-user
        mode: '0755'

    - name: Create backup script
      copy:
        content: |
          #!/bin/bash
          DATE=$(date +%Y%m%d_%H%M%S)
          BACKUP_FILE="/tmp/backup_${DATE}.tar.gz"
          tar -czf "$BACKUP_FILE" /etc /var/log 2>/dev/null
          scp -o StrictHostKeyChecking=no "$BACKUP_FILE" anscfg@yndx-ansible.practicumsuperstore.ru:"{{ remote_backup_dir }}/"
          rm -f "$BACKUP_FILE"
        dest: "{{ backup_script }}"
        owner: backup-user
        group: backup-user
        mode: '0755'

    - name: Ensure remote backup directory exists (run locally)
      delegate_to: localhost
      become: no
      run_once: true
      file:
        path: "{{ remote_backup_dir }}"
        state: directory
        owner: anscfg
        group: anscfg
        mode: '0755'

    - name: Add daily cron job for backup-user
      cron:
        name: "Daily system backup"
        user: backup-user
        minute: "0"
        hour: "2"
        job: "{{ backup_script }}"