#!/usr/bin/env ruby # # Copyright (c) 2018 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. STDOUT.sync = true require 'slop' require 'tempfile' require 'open3' $opts = Slop.parse(ARGV, strict: false, suppress_errors: true) do |o| o.banner = "Usage: zold-nohup [options] ... Run 'zold --help' for the full list of options and commands" o.bool '-h', '--help', 'Show these instructions' o.string '--log-file', 'The file to save logs into (default: ./zold-nohup.log)', default: './zold-nohup.log' o.bool '--skip-log-trim', 'Don\'t trim the log file before start (default: false)', default: false o.bool '--skip-install', 'Don\'t re-install Zold gem (default: false)', default: false o.bool '--sudo-install', 'Install Zold gem via sudo (default: false)', default: false end if $opts.help? puts($opts.to_s) exit(0) end def log(line) File.open($opts['log-file'], 'a') { |f| f.print(line) } end def exec(cmd) Open3.popen2e(cmd) do |stdin, stdout, thr| log("Started: #{cmd}") stdin.close loop do line = stdout.gets break if line.nil? log(line) end code = thr.value.exitstatus log("Exit code is #{code}: #{cmd}") raise "Exit code #{code} (non zero)" unless code.zero? end end File.delete($opts['log-file']) if File.exist?($opts['log-file']) && !$opts['skip-log-trim'] $pid = fork do Signal.trap('HUP') do print('Received HUP, ignoring...') end Signal.trap('TERM') do print('Received TERM, terminating...') exit(-1) end loop do exec("zold #{$opts.arguments.join(' ')}") exec(($opts['sudo-install'] ? 'sudo ' : '') + 'gem install zold') unless $opts['skip-install'] end end Process.detach($pid) puts($pid)