---
- name: 在Kali Linux上安装和配置VNC服务器
  hosts: kali
  become: yes
  vars:
    vnc_password: "3131"  # VNC连接密码
    vnc_port: "5901"      # VNC服务端口
    vnc_geometry: "1280x1024"  # VNC分辨率
    vnc_depth: "24"       # 颜色深度

  tasks:
    - name: 更新APT缓存
      apt:
        update_cache: yes

    - name: 安装VNC服务器和客户端
      apt:
        name:
          - tigervnc-standalone-server
          - tigervnc-viewer
          - xfce4
          - xfce4-goodies
        state: present

    - name: 创建VNC配置目录
      file:
        path: /home/ben/.vnc
        state: directory
        owner: ben
        group: ben
        mode: '0700'

    - name: 设置VNC密码
      shell: |
        echo "{{ vnc_password }}" | vncpasswd -f > /home/ben/.vnc/passwd
        echo "{{ vnc_password }}" | vncpasswd -f > /home/ben/.vnc/passwd2
      become_user: ben

    - name: 设置VNC密码文件权限
      file:
        path: /home/ben/.vnc/passwd
        owner: ben
        group: ben
        mode: '0600'

    - name: 设置VNC密码文件2权限
      file:
        path: /home/ben/.vnc/passwd2
        owner: ben
        group: ben
        mode: '0600'

    - name: 创建VNC启动脚本
      copy:
        dest: /home/ben/.vnc/xstartup
        content: |
          #!/bin/bash
          unset SESSION_MANAGER
          unset DBUS_SESSION_BUS_ADDRESS
          exec startxfce4
        owner: ben
        group: ben
        mode: '0755'

    - name: 创建VNC服务文件
      copy:
        dest: /etc/systemd/system/vncserver@.service
        content: |
          [Unit]
          Description=Start TigerVNC server at startup
          After=syslog.target network.target

          [Service]
          Type=forking
          User=ben
          Group=ben
          WorkingDirectory=/home/ben

          PIDFile=/home/ben/.vnc/%H:%i.pid
          ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
          ExecStart=/usr/bin/vncserver -depth {{ vnc_depth }} -geometry {{ vnc_geometry }} :%i
          ExecStop=/usr/bin/vncserver -kill :%i

          [Install]
          WantedBy=multi-user.target

    - name: 重新加载systemd配置
      systemd:
        daemon_reload: yes

    - name: 启用并启动VNC服务
      systemd:
        name: vncserver@1.service
        enabled: yes
        state: started

    - name: 检查VNC服务状态
      command: systemctl status vncserver@1.service
      register: vnc_status
      ignore_errors: yes

    - name: 显示VNC服务状态
      debug:
        msg: "{{ vnc_status.stdout_lines }}"

    - name: 显示VNC连接信息
      debug:
        msg: |
          VNC服务器已成功配置！
          连接信息：
          - 地址: {{ ansible_host }}
          - 端口: {{ vnc_port }}
          - 密码: {{ vnc_password }}
          - 连接命令: vnc://{{ ansible_host }}:{{ vnc_port }}
          - 使用macOS屏幕共享应用连接到上述地址