---
- block:
  - name: Create the gitea service user
    user: name={{ gitea_user }} home=/srv/gitea createhome=yes shell=/bin/bash system=yes

  - name: Create the gitea directory tree
    file: dest={{ gitea_data_dir }}/{{ item }} state=directory owner={{ gitea_user }} group={{ gitea_group }}
    with_items: '{{ gitea_data_subdirs }}'

  - name: Create the gitea conf directory
    file: dest={{ gitea_conf_dir }} state=directory owner=root group={{ gitea_group }} mode=0750

  - name: Download the gitea binary
    get_url: url={{ gitea_download_url }} dest={{ gitea_bin_path }} owner=root group={{ gitea_group }} mode=0750

  - name: Install the required packages
    package: state=present use=auto name={{ gitea_required_packages }}

  - name: Check if the gitea configuration file exists
    stat: path={{ gitea_conf_dir }}/app.ini
    register: gitea_app_ini

  - name: Change the gitea configuration. After the installation
    ini_file: path={{ gitea_conf_dir }}/app.ini section={{ item.section }} option={{ item.option }} value={{ item.value }} state={{ item.state }} owner={{ gitea_user }} group={{ gitea_group }} mode=0640 create=no
    with_items: '{{ gitea_app_configurations }}'
    when:
      - gitea_app_ini.stat.exists
      - gitea_app_configurations is defined
    notify: restart gitea

  - name: Install the gitea configuration file. At install time only
    template: src=app.ini.j2 dest={{ gitea_conf_dir }}/app.ini owner={{ gitea_user }} group={{ gitea_group }} mode=0640 force=no
    notify: restart gitea

  - name: Install the gitea systemd unit
    template: src=gitea.service.systemd dest=/etc/systemd/system/gitea.service
    register: gitea_systemd_unit

  - name: Reload the systemd configuration
    command: systemctl daemon-reload
    when: gitea_systemd_unit is changed

  - name: Ensure that the gitea service is running and enabled
    service: name=gitea status=started enabled=yes

  tags: [ 'git', 'gitea' ]