---
# Migrate devices from Prezenta app to WMT
# ──────────────────────────────────────────────────────────────────────────
# What this playbook does (in order):
#
#   1. Create /home/pi/Desktop/WMT on the target
#   2. Copy /home/pi/Desktop/WMT_project from the CONTROLLER to /home/pi/Desktop/WMT on the target
#   3. Read idmasa.txt from the target (checks Prezenta/data/ first, falls back to Prezenta/Files/ for older app models)
#   4. Write that value as work_place in WMT/data/config.txt (replaces notconfig)
#   5. Update ~/.config/wayfire.ini [autostart] start_python to launch from WMT
#   6. Rename /home/pi/Desktop/Prezenta → /home/pi/Desktop/Prezenta_Old_Data
#   7. Reboot the host
#
# Run via: Ansible > Playbooks > "Migrate to WMT" or POST /api/ansible/execute
# ──────────────────────────────────────────────────────────────────────────

- name: Migrate devices from Prezenta to WMT
  hosts: all
  gather_facts: false
  become: false

  tasks:

    # ── 1. Ensure destination directory exists ────────────────────────────
    - name: Create WMT directory on target
      file:
        path: /home/pi/Desktop/WMT
        state: directory
        owner: pi
        group: pi
        mode: '0755'

    # ── 2. Copy WMT_project from controller → target as WMT ──────────────
    - name: Copy WMT_project folder to target as /home/pi/Desktop/WMT
      copy:
        src: /home/pi/Desktop/WMT_project/
        dest: /home/pi/Desktop/WMT/
        owner: pi
        group: pi
        mode: preserve
        force: true

    # ── 3. Ensure WMT data directory exists (in case config.txt is missing)
    - name: Ensure WMT/data directory exists
      file:
        path: /home/pi/Desktop/WMT/data
        state: directory
        owner: pi
        group: pi
        mode: '0755'

    # ── 4. Read idmasa.txt – supports two Prezenta layouts ───────────────
    #       Modern layout : Prezenta/data/idmasa.txt
    #       Older layout  : Prezenta/Files/idmasa.txt
    - name: Check for idmasa.txt in modern path (Prezenta/data/)
      stat:
        path: /home/pi/Desktop/Prezenta/data/idmasa.txt
      register: idmasa_data_stat

    - name: Check for idmasa.txt in older path (Prezenta/Files/)
      stat:
        path: /home/pi/Desktop/Prezenta/Files/idmasa.txt
      register: idmasa_files_stat

    - name: Resolve idmasa.txt path (prefer data/, fall back to Files/)
      set_fact:
        idmasa_path: >-
          {{
            '/home/pi/Desktop/Prezenta/data/idmasa.txt'
            if idmasa_data_stat.stat.exists
            else '/home/pi/Desktop/Prezenta/Files/idmasa.txt'
          }}

    - name: Show which idmasa.txt will be used
      debug:
        msg: "Using idmasa.txt from: {{ idmasa_path }}"

    - name: Fail if idmasa.txt was not found in either location
      fail:
        msg: >-
          idmasa.txt not found in Prezenta/data/ or Prezenta/Files/.
          Cannot determine work_place – aborting migration.
      when:
        - not idmasa_data_stat.stat.exists
        - not idmasa_files_stat.stat.exists

    - name: Read idmasa.txt from resolved path
      slurp:
        src: "{{ idmasa_path }}"
      register: idmasa_raw

    - name: Decode idmasa value
      set_fact:
        work_place_value: "{{ idmasa_raw.content | b64decode | trim }}"

    - name: Show detected work_place value
      debug:
        msg: "work_place will be set to: '{{ work_place_value }}'"

    # ── 5. Write work_place into WMT/data/config.txt ──────────────────────
    #       Uses Python (always available on Raspberry Pi) to correctly
    #       read/write the INI file and set work_place inside [device].
    #       Also resets last_synced to epoch so first startup does NOT
    #       overwrite work_place with a potentially empty server value.
    - name: Set work_place in WMT config.txt via Python
      ansible.builtin.shell:
        cmd: |
          python3 - <<'PYEOF'
          import configparser, os
          path = '/home/pi/Desktop/WMT/data/config.txt'
          p = configparser.ConfigParser()
          p.read(path)
          if not p.has_section('chrome'):
              p.add_section('chrome')
          if not p.has_section('card_api'):
              p.add_section('card_api')
          if not p.has_section('server'):
              p.add_section('server')
          if not p.has_section('device'):
              p.add_section('device')
          if not p.has_section('meta'):
              p.add_section('meta')
          p.set('device', 'work_place', '{{ work_place_value }}')
          # Reset last_synced so first startup pull from server does not
          # overwrite the work_place we just set (server will return the
          # correct device_name once this device checks in).
          p.set('meta', 'last_synced', '1970-01-01T00:00:00')
          os.makedirs(os.path.dirname(path), exist_ok=True)
          with open(path, 'w') as f:
              p.write(f)
          print('work_place set to: {{ work_place_value }}')
          PYEOF

    - name: Confirm work_place change
      command: grep 'work_place' /home/pi/Desktop/WMT/data/config.txt
      register: wp_check
      changed_when: false

    - name: Show work_place line in config.txt
      debug:
        msg: "{{ wp_check.stdout }}"

    # ── 6. Update wayfire.ini autostart to launch from WMT ───────────────
    - name: Update wayfire.ini start_python path from Prezenta to WMT
      lineinfile:
        path: /home/pi/.config/wayfire.ini
        regexp: "^start_python\\s*=.*"
        line: "start_python = lxterminal -e \"bash -c 'cd /home/pi/Desktop/WMT; python3 app.py; exec bash'\""
        backrefs: false
        backup: true

    - name: Confirm wayfire.ini change
      command: grep "start_python" /home/pi/.config/wayfire.ini
      register: wayfire_check
      changed_when: false

    - name: Show wayfire.ini start_python line
      debug:
        msg: "{{ wayfire_check.stdout }}"

    # ── 7. Kill any running Prezenta app.py before renaming ──────────────
    - name: Kill any process running from Prezenta app.py
      shell: pkill -f "python3.*Prezenta/app.py"
      ignore_errors: true
      changed_when: false

    - name: Wait a moment for the process to terminate
      wait_for:
        timeout: 3

    # ── 8. Rename Prezenta → Prezenta_Old_Data ─────────────────────────── #
    - name: Check if Prezenta folder exists
      stat:
        path: /home/pi/Desktop/Prezenta
      register: prezenta_stat

    - name: Check if Prezenta_Old_Data already exists
      stat:
        path: /home/pi/Desktop/Prezenta_Old_Data
      register: prezenta_old_stat

    - name: Rename Prezenta to Prezenta_Old_Data
      command: mv /home/pi/Desktop/Prezenta /home/pi/Desktop/Prezenta_Old_Data
      when:
        - prezenta_stat.stat.exists
        - not prezenta_old_stat.stat.exists

    - name: Warn if Prezenta_Old_Data already exists (rename skipped)
      debug:
        msg: "⚠ Prezenta_Old_Data already exists — rename skipped to avoid overwrite."
      when: prezenta_old_stat.stat.exists

    # ── 9. Reboot ─────────────────────────────────────────────────────────
    - name: Reboot host to apply all changes
      become: true
      reboot:
        msg: "Rebooting after WMT migration"
        reboot_timeout: 180
        pre_reboot_delay: 3
        post_reboot_delay: 15
