---
- hosts: all
  vars:
    deploy_path: /www/wwwroot/xiaoding
    timestamp: "{{ ansible_date_time.year }}-{{ ansible_date_time.month }}-{{ ansible_date_time.day }}-{{ ansible_date_time.hour }}:{{ ansible_date_time.minute }}:{{ ansible_date_time.second }}"
    backup_file: "xiaoding_backup_{{ timestamp }}.tar.gz"
    project_archive: "owl-admin.tar.gz"

  tasks:
    - name: Create backup of existing deployment
      archive:
        path: "{{ deploy_path }}"
        dest: "/tmp/{{ backup_file }}"
        format: gz
      ignore_errors: yes

    - name: Create local project archive
      local_action:
        module: archive
        path: "{{ playbook_dir }}/../../*"
        dest: "/tmp/{{ project_archive }}"
        format: gz
        exclude_path:
          - "*.git"
          - "node_modules"
          - "vendor"
      run_once: true

    - name: Ensure deploy directory exists
      file:
        path: "{{ deploy_path }}"
        state: directory
        mode: '0755'

    - name: Copy project archive to remote
      copy:
        src: "/tmp/{{ project_archive }}"
        dest: "/tmp/{{ project_archive }}"

    - name: Clean deploy directory
      file:
        path: "{{ deploy_path }}"
        state: absent

    - name: Create deploy directory
      file:
        path: "{{ deploy_path }}"
        state: directory
        mode: '0755'

    - name: Extract project archive
      unarchive:
        src: "/tmp/{{ project_archive }}"
        dest: "{{ deploy_path }}"
        remote_src: yes

    - name: Copy .env file from root
      copy:
        src: /root/.env
        dest: "{{ deploy_path }}/.env"
        remote_src: yes
      ignore_errors: yes

    - name: Set proper permissions
      file:
        path: "{{ deploy_path }}"
        owner: www
        group: www
        recurse: yes
        mode: '0777'

    - name: Clean up remote archive
      file:
        path: "/tmp/{{ project_archive }}"
        state: absent

    - name: Clean up local archive
      local_action:
        module: file
        path: "/tmp/{{ project_archive }}"
        state: absent
      run_once: true