---
# Copyright 2021-2023 Anthony Perkins
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

- name: Detect Emacs binary
  ansible.builtin.stat:
    path: "{{ prefix }}/bin/emacs"
  vars:
    prefix: "{{ '/usr' if ansible_system == 'Linux' else '/usr/pkg' if ansible_system == 'NetBSD' else '/usr/local' }}"
  register: emacs_binary
- name: Remove ~/.emacs file
  ansible.builtin.file:
    path: "{{ ansible_env.HOME }}/.emacs"
    state: absent
- name: Clone Emacs settings
  ansible.builtin.git:
    repo: https://github.com/acperkins/emacs.d.git
    dest: "{{ ansible_env.HOME }}/.emacs.d"
- name: Create Emacs user service (Linux)
  ansible.builtin.template:
    src: emacs.service
    dest: "{{ ansible_env.XDG_CONFIG_HOME }}/systemd/user/emacs.service"
  vars:
    prefix: "{{ '/usr' if ansible_system == 'Linux' else '/usr/pkg' if ansible_system == 'NetBSD' else '/usr/local' }}"
  when: ansible_system == 'Linux' and emacs_binary.stat.exists == True
- name: Add Emacs server to autostart (FreeBSD)
  ansible.builtin.copy:
    src: '{{ ansible_env.HOME }}/.emacs.d/emacs-server.desktop'
    dest: '{{ ansible_env.XDG_CONFIG_HOME }}/autostart'
    remote_src: yes
  when: ansible_system == 'FreeBSD' and emacs_binary.stat.exists == True
- name: Start Emacs user service
  ansible.builtin.systemd:
    name: emacs.service
    scope: user
    daemon_reload: yes
    enabled: yes
    state: started
  when: ansible_system == 'Linux' and emacs_binary.stat.exists == True
- name: Create Emacs client launcher
  ansible.builtin.copy:
    src: "{{ ansible_env.HOME }}/.emacs.d/emacs-client.desktop"
    dest: "{{ ansible_env.XDG_DATA_HOME }}/applications/emacs.desktop"
    remote_src: yes
  when: emacs_binary.stat.exists == True