---

- name: Install required by mastodon
  apt:
    name: "{{ requiredPackages }}"
    state: present

- name: ensure postgresql is running
  service:
    name: postgresql
    state: restarted

- name: Create postgresql User Mastodon
  become: yes
  become_user: postgres
  shell: psql -c "CREATE USER mastodon CREATEDB;"

- name: Create Mastodon Database for restauration
  become: yes
  become_user: "{{ username }}"
  shell: |
    createdb -T template0 -E UTF8 mastodon_production
  args:
    executable: /bin/bash
  when: restore == True

- name: Install Mastodon from git
  become: yes
  become_user: "{{ username }}"
  shell: |
    cd
    export PATH="$HOME/.rbenv/bin:$PATH"
    eval "$(rbenv init -)"
    git clone https://github.com/tootsuite/mastodon.git live
    cd live
    git checkout v"{{ mastodon_version }}"
    gem install bundler --no-document
    bundle config set deployment 'true'
    bundle config set without 'development test'
    bundle install
  args:
    executable: /bin/bash

- name: Exec yarn install
  become: yes
  become_user: "{{ username }}"
  ignore_errors: True
  shell: |
    cd
    export PATH="$HOME/.rbenv/bin:$PATH"
    eval "$(rbenv init -)"
    cd live
    yarn install --pure-lockfile --non-interactive
  args:
    executable: /bin/bash


- name: Copy nginx configuration
  copy:
    src: /home/{{ username }}/live/dist/nginx.conf
    dest: /etc/nginx/sites-available/mastodon.conf
    owner: root
    group: root
    remote_src: yes

- name: Set server name in nginx configuration
  replace:
    path: /etc/nginx/sites-available/mastodon.conf
    regexp: "^.*server_name example.com;"
    replace: "  server_name {{ domain }};"


- name: Set root directory in nginx configuration
  replace:
    dest: /etc/nginx/sites-available/mastodon.conf
    regexp: "^.*root /home/mastodon/live/public;"
    replace: "root /home/{{ username}}/live/public;"


- name: Create a symbolic link
  file:
    src: /etc/nginx/sites-available/mastodon.conf
    dest: /etc/nginx/sites-enabled/mastodon.conf
    owner: root
    group: root
    state: link

- name: Copy systemd services
  shell: |
    cp /home/"{{ username }}"/live/dist/mastodon-web.service /etc/systemd/system/
    cp /home/"{{ username }}"/live/dist/mastodon-sidekiq.service /etc/systemd/system/
    cp /home/"{{ username }}"/live/dist/mastodon-streaming.service /etc/systemd/system/

- name: Enable systemd service
  shell: |
    systemctl enable mastodon-web
    systemctl enable mastodon-sidekiq
    systemctl enable mastodon-streaming