---
- name: Setup and manage frpc
  hosts: frpclient
  become: true
  tasks:
    - name: Create mall directory if not exists
      file:
        path: /root/mall
        state: directory
        mode: '0755'

    - name: Create frp directory if not exists
      file:
        path: /root/frp
        state: directory
        mode: '0755'

    - name: Copy frp directory
      ansible.builtin.copy:
        src: frp
        dest: /root
        mode: '0644'
        force: true

    - name: Copy frpc binary to /usr/local/bin
      copy:
        src: "../../script/ansible/frp/frpc"
        dest: "/usr/local/bin/frpc"
        mode: '0755'

    - name: Create systemd service file
      copy:
        dest: /etc/systemd/system/frpc.service
        content: |
          [Unit]
          Description=frpc service
          After=network.target

          [Service]
          Type=simple
          User=root
          ExecStart=/usr/local/bin/frpc -c /root/frp/frpc.toml
          Restart=always
          RestartSec=5

          [Install]
          WantedBy=multi-user.target
        mode: '0644'

    - name: Start and enable frpc service
      systemd:
        name: frpc
        state: restarted
        enabled: true
        daemon_reload: true

    - name: Check frpc service status
      command: systemctl status frpc
      register: frpc_status
      changed_when: false
      ignore_errors: true
