---
- block:
    - name: Creating "{{ stcp_base_dir }}" directory
      file: path="{{ stcp_base_dir }}" state=directory
    - name: Copying the STCP binary file
      copy: 
        src: multi_srv_raw
        dest: '{{ stcp_binary_path }}'
        mode: '0700'
        backup: yes
      when: ansible_architecture == "x86_64"
    - name: Copying the STCP binary file
      copy: 
        src: multi_srv_arm64
        dest: '{{ stcp_binary_path }}'
        mode: '0700'
        backup: yes
      when: ansible_architecture == "aarch64"

- name: Copying the loop script file
  copy:
    src: loop
    dest: '{{ loop_script_path }}'
    mode: '0700'

- block:
    - name: Creating STCP instance directory
      file: 
        path: '{{ stcp_instance_dir }}'
        state: directory
        mode: '0600'
    - name: Creating symlink to the STCP binary file
      file:
        src: '{{ stcp_binary_path }}'
        dest: '{{ stcp_instance_dir }}/multi_srv_raw'
        state: link

- block:
    - name: Checking logging file existence
      stat:
        path: '{{ clients_log_file_path }}'
      register: logfile
    - name: Creating STCP logging file
      file:
        path: '{{ clients_log_file_path }}'
        state: touch
        mode: '0600'
      when: use_client_logging == true and not logfile.stat.exists

- block:
    - name: Checking users file existence
      stat:
        path: '{{ users_file_path }}'
      register: usersfile
    - name: Creating STCP users file
      file:
        path: '{{ users_file_path }}'
        state: touch
        mode: '0600'
      when: use_auth == true and not usersfile.stat.exists

- name: Templating STCP server config
  template:
    src: server.ini.j2
    dest: '{{ stcp_instance_dir }}/server.ini'
    mode: '0600'

- block:
    - file: 
        path: '{{ stcp_scripts_dir }}'
        state: directory
        mode: '0600' 
    - name: Templating L2 scripts
      template: 
        src: up.j2
        dest: '{{ stcp_scripts_dir }}/up.sh'
        mode: '0700'
    - template: 
        src: down.j2
        dest: '{{ stcp_scripts_dir }}/down.sh'
        mode: '0700'
  when: stcp_level|lower == "l2"

- name: Insert info about instance
  lineinfile:
    path: '{{ stcp_base_dir }}/.instances'
    create: yes
    line: 'stcp_{{ stcp_instance_name }}'
    state: present