---
# Update WMT client code from the controller's WMT_project folder
# ──────────────────────────────────────────────────────────────────────────
# Use this for devices that have not yet received the HTTP auto-update,
# or whenever you need to force a code push from the server.
#
# What this playbook does:
#   1. Ensure WMT directory exists on the target
#   2. Back up the current app.py as app.py.bak.<version>
#   3. Copy everything from /home/pi/Desktop/WMT_project/ on the CONTROLLER
#      → /home/pi/Desktop/WMT/ on the TARGET
#      The data/ directory on the target is fully preserved (never touched)
#   4. Fix file ownership
#   5. Restart the wmt systemd service
#
# The data/ directory (config.txt, idmasa.txt, tag.txt, log.txt, device_info.txt)
# is intentionally excluded — device-specific settings stay intact.
#
# Run via: Ansible > Playbooks > "Update WMT Code"
# ──────────────────────────────────────────────────────────────────────────

- name: Update WMT client code from WMT_project folder
  hosts: all
  gather_facts: false
  become: false

  vars:
    controller_src: /home/pi/Desktop/WMT_project/
    wmt_dir: /home/pi/Desktop/WMT

  tasks:

    # ── 1. Ensure WMT directory exists ────────────────────────────────────
    - name: Ensure WMT directory exists on target
      file:
        path: "{{ wmt_dir }}"
        state: directory
        owner: pi
        group: pi
        mode: '0755'

    # ── 2. Back up current app.py ─────────────────────────────────────────
    - name: Read first line of current app.py (for backup filename)
      shell: head -1 {{ wmt_dir }}/app.py 2>/dev/null || echo "unknown"
      register: local_first_line
      changed_when: false
      ignore_errors: true

    - name: Extract local version number
      set_fact:
        local_version: >-
          {{ local_first_line.stdout
             | regex_search('version\s+([\d.]+)', '\1')
             | first | default('old') }}

    - name: Back up current app.py
      copy:
        src: "{{ wmt_dir }}/app.py"
        dest: "{{ wmt_dir }}/app.py.bak.{{ local_version }}"
        remote_src: true
        owner: pi
        group: pi
        mode: preserve
      ignore_errors: true

    - name: Show backup info
      debug:
        msg: "Backed up app.py v{{ local_version }} → app.py.bak.{{ local_version }}"

    # ── 3. Snapshot data/ before copy (audit) ────────────────────────────
    - name: List current data/ files (audit)
      shell: ls -1 {{ wmt_dir }}/data/ 2>/dev/null || echo "(empty or missing)"
      register: data_files_before
      changed_when: false

    - name: Show data/ files that will be preserved
      debug:
        msg: "data/ contents (will NOT be changed): {{ data_files_before.stdout_lines }}"

    # ── 4. Sync WMT_project → WMT on target, excluding data/ ─────────────
    #       synchronize uses rsync under the hood; delegate_to pushes
    #       from the controller to the target.
    - name: Sync WMT_project to target (exclude data/ and junk files)
      synchronize:
        src: "{{ controller_src }}"
        dest: "{{ wmt_dir }}/"
        recursive: true
        delete: false
        checksum: true
        rsync_opts:
          - "--exclude=data/"
          - "--exclude=.git/"
          - "--exclude=.gitignore"
          - "--exclude=__pycache__/"
          - "--exclude=*.pyc"
          - "--exclude=*.pyo"
          - "--exclude=*.log"
          - "--exclude=*.bak"
          - "--exclude=venv/"
          - "--exclude=.venv/"
          - "--exclude=node_modules/"
          - "--exclude=.*"
      register: sync_result

    - name: Show sync summary
      debug:
        msg: "Sync completed. Changed: {{ sync_result.changed }}"

    # ── 5. Fix ownership ──────────────────────────────────────────────────
    - name: Set correct ownership on WMT directory
      become: true
      file:
        path: "{{ wmt_dir }}"
        owner: pi
        group: pi
        recurse: true

    # ── 6. Verify data/ is still intact ──────────────────────────────────
    - name: List data/ files after update (verification)
      shell: ls -1 {{ wmt_dir }}/data/ 2>/dev/null || echo "(empty)"
      register: data_files_after
      changed_when: false

    - name: Show data/ contents after update (should match before)
      debug:
        msg: "{{ data_files_after.stdout_lines }}"
        
   # ── 9. Reboot ─────────────────────────────────────────────────────────
    - name: Reboot host to apply all changes
      become: true
      reboot:
        msg: "Rebooting after WMT code update "
        reboot_timeout: 180
        pre_reboot_delay: 3
        post_reboot_delay: 15