#!/usr/bin/env ruby require 'fileutils' require 'optparse' #View process journalctl -u lipigas_rails -f -o cat -n 200 #JENKINS RUN SCRIPT --- https://www.cyberciti.biz/tips/allow-a-normal-user-to-run-commands-as-root.html METHOD, INPUT = ARGV @base_path = File.expand_path File.dirname(__FILE__) @base_path_systemctl = '/etc/systemd/system' def verify_sh(file) raise "Archivo no contiene es un .sh" unless file.include?(".sh") end def constructor_systemctl(file) parse = file.split("_") client_name = parse[0].capitalize project_name = parse[1].capitalize framework_name = parse[2].capitalize str = "[Unit]"+ "\n" str += "Description=#{client_name} #{project_name} #{framework_name} Service" + "\n" str += "After=network.target" + "\n" str += "[Service]" + "\n" str += "Type=simple" + "\n" str += "User=root" + "\n" str += "WorkingDirectory=#{@base_path}" + "\n" str += "ExecStart=#{@base_path}/#{file}.sh" + "\n" str += "Restart=always" + "\n" str += "RestartSec=2" + "\n" str += "[Install]" + "\n" str += "WantedBy=multi-user.target" return str end def write_file(file,input) File.open("#{@base_path_systemctl}/#{file}.service", 'w') { |file| file.write(input) } end def list_all_service_name(project) puts "Archivos listados en: #{@base_path_systemctl}" system("ls /etc/systemd/system | grep #{project}") end def make_restart(files) str = "#!/bin/bash"+ "\n" files.each do |file| str += "systemctl restart #{file.gsub(".sh", '')}" + "\n" end File.open("#{@base_path}/restart.sh", 'w') { |file| file.write(str) } end def enable_systemctl(file) system("systemctl enable #{file}") end def search_files(name) files = Dir.entries(".").select do |entry| entry.include?(name) && entry.include?(".sh") end return files end case METHOD when "project" files = search_files(INPUT) make_restart(files) files.each do |file| verify_sh(file) file = file.gsub(".sh", '') output = constructor_systemctl(file) write_file(file,output) enable_systemctl(file) end list_all_service_name(INPUT) when "only" verify_sh(INPUT) file = INPUT.gsub(".sh", '') output = constructor_systemctl(file) write_file(file,output) enable_systemctl(file) list_all_service_name(file) else puts "Nada" end