---
# Before running this script you need the following:
# - 2 RockyLinux 9 minimal install servers with static ips defined 
#     in order to configure a static ip:
#       1. type nmtui in console
#       2. Edit a connection
#       3. Choose the interface (enp0s8 in my case) and select Edit...
#       4. Go to IPv4 CONFIGURATION and set from Automatic to Manual then select Show
#       5. Type the desired address alongside Addresses field then click OK then click Back
#       6. Go to Activate a connection
#       7. Deactivate the enp0s8 connection and activate it again to apply the changes
# - after the user creation below, to set up a passwordless ssh connection from the yum host created user to the pkg host created user(otherwise a yes/no prompt will be encountered
#   and disrupt the script)

- hosts: pkg, yum
  vars: 
    ansible_user: root
  tasks:
    - name: Make sure we have a 'admin' group
      group:
        name: admin
        state: present

    - name: Allow 'admin' group to have passwordless sudo
      lineinfile:
        dest: /etc/sudoers
        state: present
        regexp: '^%admin'
        line: '%admin ALL=(ALL) NOPASSWD: ALL'
        validate: 'visudo -cf %s'

    - name: Add sudoers users to admin group
      user:
        name={{ user }}
        groups=admin
        append=yes
        state=present
        createhome=yes

    - name: get the username running the deploy
      become: false
      local_action: command whoami
      register: host_username

    - name: Set up authorized keys for the {{ user }} user
      authorized_key: user={{ user }} key="{{ item }}"
      with_file:
        - '/home/{{ host_username.stdout }}/.ssh/id_rsa.pub'

- hosts: yum
  vars:
    # CGRateS location
    cgrates_dir: "/home/{{ user }}/go/src/github.com/cgrates/cgrates"
    cgrates_branch: "master"
    cgrates_distribution: "nightly"
    ###############################################################
    ##################### GPG Vars #############################
    ###############################################################
    gpg_home: "/root"
    gpg_realname: "CGRateS"
    gpg_useremail: "cgrates@itsyscom.com"
    gpg_pubkeyfileexport: "yum.cgrates.org.gpg.key"

    gpg_keylength: 2048
    gpg_subkeylength: 2048
    gpg_expire: 360

    rootUser : root

    customPath: "{{ lookup('env','PATH') }}:/home/{{ user }}/go/bin:/usr/local/go/bin:{{ ansible_env.PATH }}"

    ansible_user: '{{ user }}'
  tasks:
    - name: set cgrates cgrates_distribution
      set_fact:
        cgrates_distribution: "{{ cgrates_distribution }}"
# ###########################################################################################################################
# ###########################################################################################################################
# # install dependencies
    - name: Add epel-relase repo so we can install sshpass
      become: true
      shell: "yum install epel-release -y"

    - name: Install dependencies
      become: yes
      yum:
        name:
          - git
          - nginx
          - rpm
          - rpm-build
          - rpm-sign
          - createrepo
          - wget
          - gnupg2
          - sshpass
          - tar
        state: present
# ###########################################################################################################################
# ###########################################################################################################################
# Prepare for configuration
    - name: set cgrates distribution
      set_fact:
        cgrates_distribution: "{{ cgrates_branch }}"
      when: cgrates_branch != "master"

    - name: Check if /var/packages/yum directory exists
      become: true
      file:
        path: /var/packages/yum
        state: directory

    - name: Check if /var/packages/yum/{{ cgrates_distribution }} directory exists
      become: true
      file:
        path: /var/packages/yum/{{ cgrates_distribution }}
        state: directory

    - name: Nginx on CentOS needs additional permissions
      become: true
      shell: "sudo chcon -t httpd_sys_content_t /var/packages/ -R"

    - name: Nginx on CentOS needs additional permissions2
      become: true
      shell: "sudo chcon -t httpd_sys_rw_content_t /var/packages/ -R"
        
    - name: Generate GPG Key
      include: gpg.yaml

    - name: Check if NGINX needs to be configured
      become: true
      shell: "ls /etc/nginx/ | grep 'nginx.conf.original'"
      ignore_errors: true
      register: nginxConfig

    - name: Configure NGINX server
      include: nginx.yaml
      when: nginxConfig.stdout_lines|length < 1

    - name: Enable and start nginx
      become: true
      systemd:
        name: nginx
        state: started
        masked: no
        enabled: yes

    - name: Add .rpmmacros in root directory
      become: true
      template:
        src: rpmmacros.j2
        dest: "{{ gpg_home }}/.rpmmacros"
        mode: '0600'
        owner: "{{ rootUser }}"
        
    - name: Import the key in rpm
      become: true
      shell: rpm --import /var/packages/yum.cgrates.org.gpg.key
      args:
        warn: false

###########################################################################################################################
###########################################################################################################################
# Install Go
- name: Install Go
    import_role:
      name: ../roles/go

###########################################################################################################################
###########################################################################################################################
# Install CGRateS
    - name: create cgrates directory
      become: yes
      file:
        state: directory
        mode: 'u=rwx,go=rx'
        owner: "{{ user }}"
        group: "{{ user }}"
        dest: '{{ cgrates_dir }}'
      become_user: "{{ user }}"

    - name: git clone cgrates
      git:
        repo: https://github.com/cgrates/cgrates.git
        dest: '{{ cgrates_dir }}'
        update: yes
        force: yes
        version: "{{ cgrates_branch }}"
      become: yes
      become_user: "{{ user }}"

    - name: clean go cache
      become: yes
      shell: "go clean --cache"
      environment:
        PATH: "{{ lookup('env','PATH') }}:/home/{{ user }}/go/bin:/usr/local/go/bin:{{ ansible_env.PATH }}"

    - name: clean go modcache
      become: yes
      shell: "go clean --modcache"
      environment:
        PATH: "{{ lookup('env','PATH') }}:/home/{{ user }}/go/bin:/usr/local/go/bin:{{ ansible_env.PATH }}"

    - name: sync the go mod with vendor
      become: yes
      shell: "go mod vendor"
      environment:
        PATH: "{{ lookup('env','PATH') }}:/home/{{ user }}/go/bin:/usr/local/go/bin:{{ ansible_env.PATH }}"
      args:
        chdir: '{{ cgrates_dir }}'

    - name:  build cgrates
      shell: "sh {{ cgrates_dir }}/build.sh"
      environment:
        PATH: "{{ lookup('env','PATH') }}:/home/{{ user }}/go/bin:/usr/local/go/bin:{{ ansible_env.PATH }}"
      args:
        chdir: '{{ cgrates_dir }}'
        
    - name: get git version
      shell: git rev-parse HEAD
      register: gitVersion
      args:
        chdir: '{{ cgrates_dir }}'
    
    - name: get git short version
      shell: git log -1 --format=%ci | date +%Y%m%d%H%M%S
      register: gitDate
      args:
        chdir: '{{ cgrates_dir }}'
    
    - name: get git date
      shell: git rev-parse --short HEAD
      register: gitShortVersion
      args:
        chdir: '{{ cgrates_dir }}'

    - name: get git tag
      shell: "git tag -l --points-at HEAD"
      args:
        chdir: '{{ cgrates_dir }}'
      register: gitTagVar

    - name: Compose the ReleaseTag
      set_fact:
        releaseTag: ""

    - name: Compose the ReleaseTag with values
      set_fact:
        releaseTag: "{{ gitDate.stdout_lines[0] }}+{{ gitShortVersion.stdout_lines[0] }}"
      when : gitTagVar.stdout_lines|length == 0
###########################################################################################################################
###########################################################################################################################
# Generate package
    - name: Create the folders for build
      become: yes
      file:
        path: cgr_build/{{ item.dirName }}
        state: directory
      loop:
        - { dirName: BUILD }
        - { dirName: SOURCES }
        - { dirName: SPECS }
        - { dirName: SRPMS }
        - { dirName: RPMS }
       
    - name: Download the tar.gz for the last commit
      become: yes
      get_url:
        url: https://github.com/cgrates/cgrates/archive/{{ cgrates_branch }}/{{ gitVersion.stdout_lines[0] }}.tar.gz
        dest: cgr_build/SOURCES/{{ gitVersion.stdout_lines[0] }}.tar.gz
     
    - name: Add cgrates.spec in SPECS
      become: yes
      template:
        src: cgrates.spec.j2
        dest: cgr_build/SPECS/cgrates.spec
        
    - name: Generate the .rpm file
      become: yes
      shell: 'rpmbuild -bb --define "_topdir /home/{{ user }}/cgr_build" cgr_build/SPECS/cgrates.spec'
      environment:
        PATH: "{{ lookup('env','PATH') }}:/home/{{ user }}/go/bin:/usr/local/go/bin:{{ ansible_env.PATH }}"
        
    - name: Take the name of the .rpm package
      become: yes
      shell : "ls cgr_build/RPMS/x86_64/ | grep '.rpm'"
      register: rmpFileName
    
    # Move the file to PKG server
    - name: Copy the file to PKG server
      shell: 'scp cgr_build/RPMS/x86_64/{{ item }} {{ pkgAddr }}:/tmp/' 
      with_items: '{{ rmpFileName.stdout_lines }}'
    
    - name: Sign with rpm --addsign the .rpm file
      become: yes
      shell: 'sudo rpm --addsign cgr_build/RPMS/x86_64/{{ item }}'
      with_items: "{{ rmpFileName.stdout_lines }}"
      when : cgrates_branch == "master" or gitTagVar.stdout_lines|length > 0
      
    - name: Check if is something in /var/packages/yum/{{ cgrates_distribution }}
      become: yes
      shell : "ls /var/packages/yum/{{ cgrates_distribution }}/"
      register: yumFiles
      when : cgrates_branch == "master" or gitTagVar.stdout_lines|length > 0

      #Clean the folder
    - name: Clean the incoming folder
      become: yes
      shell: "sudo rm -rf /var/packages/yum/{{ cgrates_distribution }}/*"
      when: (cgrates_branch == "master" or gitTagVar.stdout_lines|length > 0) and yumFiles.stdout_lines|length > 1
    
    - name: Move the files to /var/packages/yum/{{ cgrates_distribution }}
      become: yes
      command: mv cgr_build/RPMS/x86_64/{{ item }} /var/packages/yum/{{ cgrates_distribution }}/
      with_items: "{{ rmpFileName.stdout_lines }}"
      when: (cgrates_branch == "master" or gitTagVar.stdout_lines|length > 0) and rmpFileName.stdout_lines|length > 0

    - name: Include the package with createrepo
      become: yes
      shell: createrepo /var/packages/yum/{{ cgrates_distribution }}
      when : cgrates_branch == "master" or gitTagVar.stdout_lines|length > 0

    - name: Remove rpm files
      become: yes
      file:
        path: cgr_build/RPMS/x86_64/{{ item }}
        state: absent
      with_items: "{{ rmpFileName.stdout_lines }}"
      when: cgrates_branch != "master" and gitTagVar.stdout_lines|length == 0

    - name: Nginx on CentOS needs additional permissions for the new rpmfile
      become: true
      shell: "sudo chcon -t httpd_sys_content_t /var/packages/ -R"

    - name: Nginx on CentOS needs additional permissions2 for the new rpmfile
      become: true
      shell: "sudo chcon -t httpd_sys_rw_content_t /var/packages/ -R"

- hosts: pkg
  vars:
    ansible_python_interpreter: auto # to disable deprication warning related to the use of python2
    ansible_user: '{{ user }}'
  tasks:
    - name: set cgrates cgrates_distribution
      set_fact:
        cgrates_distribution: "{{ hostvars['yum']['cgrates_distribution'] }}"

    - name: Creates directory
      become: yes
      file:
        path: /var/packages/rpm/{{ cgrates_distribution }}/
        state: directory
        
    - name: Remove symlink from current rpm package
      become: yes
      file:
        path: /var/packages/rpm/{{ cgrates_distribution }}/cgrates_current.rpm
        state: absent
      when : cgrates_distribution == "nightly" or hostvars['yum']['gitTagVar'].stdout_lines|length > 0

    - name: Move the new package to /var/packages/rpm
      become: yes
      shell: "mv /tmp/{{ item }} /var/packages/rpm/{{ cgrates_distribution }}/"
      with_items: "{{ hostvars['yum']['rmpFileName']['stdout_lines'] }}"

    - name: Create the new symlink cgrates_current.rpm
      become: yes
      file:
        src: /var/packages/rpm/{{ cgrates_distribution }}/{{ item }}
        dest: /var/packages/rpm/{{ cgrates_distribution }}/cgrates_current.rpm
        state: link
      with_items: "{{ hostvars['yum']['rmpFileName']['stdout_lines'] }}"
      when : cgrates_distribution == "nightly" or hostvars['yum']['gitTagVar'].stdout_lines|length > 0
