---
- name: Setup Xfce desktop environment and Chrome Dev for browser automation
  hosts: browser
  become: yes
  vars:
    target_user: ben

  tasks:
    - name: Update package lists
      apt:
        update_cache: yes
        cache_valid_time: 3600

    - name: Install Xfce desktop environment
      apt:
        name:
          - xfce4
          - xfce4-goodies
          - lightdm
          - xorg
          - dbus-x11
        state: present

    - name: Install additional useful packages for desktop environment
      apt:
        name:
          - firefox-esr
          - geany
          - thunar-archive-plugin
          - xfce4-terminal
          - gvfs
          - fonts-noto
          - fonts-noto-cjk
        state: present

    - name: Download Google Chrome Dev .deb package
      get_url:
        url: https://dl.google.com/linux/direct/google-chrome-unstable_current_amd64.deb
        dest: /tmp/google-chrome-unstable_current_amd64.deb
        mode: '0644'

    - name: Install Google Chrome Dev
      apt:
        deb: /tmp/google-chrome-unstable_current_amd64.deb

    - name: Clean up downloaded .deb package
      file:
        path: /tmp/google-chrome-unstable_current_amd64.deb
        state: absent

    - name: Install Chrome automation dependencies
      apt:
        name:
          - python3-pip
          - python3-venv
          - python3-dev
          - build-essential
          - libssl-dev
          - libffi-dev
        state: present

    - name: Install Python packages for browser automation
      pip:
        name:
          - selenium
          - webdriver-manager
          - pyvirtualdisplay
        executable: pip3

    - name: Set up Xfce as default desktop environment
      copy:
        dest: /etc/lightdm/lightdm.conf
        content: |
          [Seat:*]
          autologin-user={{ target_user }}
          autologin-user-timeout=0
          autologin-session=xfce
          user-session=xfce

    - name: Ensure user is in necessary groups
      user:
        name: "{{ target_user }}"
        groups:
          - audio
          - video
          - input
          - netdev
        append: yes

    - name: Create .xprofile for user
      copy:
        dest: /home/{{ target_user }}/.xprofile
        content: |
          # Start Xfce on login
          startxfce4
        owner: "{{ target_user }}"
        group: "{{ target_user }}"
        mode: '0644'

    - name: Enable and start lightdm service
      systemd:
        name: lightdm
        enabled: yes
        state: started

    - name: Display success message
      debug:
        msg: "Xfce desktop environment and Chrome Dev have been configured for user {{ target_user }} on {{ inventory_hostname }}"

  handlers:
    - name: restart lightdm
      systemd:
        name: lightdm
        state: restarted