fgrehm/vagrant-notify

View on GitHub
files/notify-send.erb

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby
# -*- mode: ruby -*-
# vi: set ft=ruby :

# This is the wrapper around notify-send that connects to the host machine when sending notifications.

require 'rubygems'
require 'socket'
require 'optparse'
require 'fileutils'
require 'json'

options = {}
OptionParser.new do |opts|
opts.banner = "Usage: notify-send.rb TITLE [MESSAGE] [options]"

  opts.on('-u', '--urgency LEVEL')           { |v| options[:urgency] = v }
  opts.on('-t', '--expire-time TIME')        { |v| options[:expire_time] = v }
  opts.on('-a', '--app-name APP_NAME')       { |v| options[:app_name] = v }
  opts.on('-i', '--icon ICON[,ICON...]')     { |v| options[:icon] = v }
  opts.on('-c', '--category TYPE[,TYPE...]') { |v| options[:category] = v }
  opts.on('-h', '--hint TYPE:NAME:VALUE')    { |v| options[:hint] = v }
  opts.on('-v', '--version')                 { |v| options[:version] = v }
end.parse!

options[:title]=ARGV.pop
options[:message]=ARGV.pop if ARGV.length > 0

# BSD guests do not support shared folders
unless RUBY_PLATFORM =~ /freebsd|openbsd|netbsd/
  if options[:icon]
    new_filename = options[:icon].gsub('/', '-')
    FileUtils.cp options[:icon], "<%= shared_folder %>/#{new_filename}"
    options[:icon]  = new_filename
  end
end

cmd = JSON.generate(options, quirks_mode: true)

# VirtualBox is the only provider that can communicate with 127.0.0.1, others will have to use default private networking
if "<%= provider_name %>" == "virtualbox"
  if RUBY_PLATFORM =~ /linux/
    client_ip = `ip route|awk '/default/ {print $3}'`
  elsif RUBY_PLATFORM =~ /solaris|freebsd|openbsd|netbsd/
    client_ip = `netstat -r|awk '/default/ {print $2}'`
  end
else
  client_ip = "<%= client_ip %>"
end

TCPSocket.open client_ip.strip, <%= host_port %> do |s|
  s.send cmd, 0
end