# Connected clients per SSID and band, from the rXg's connected_clients table
# (distinct MACs whose row was refreshed in the last MINUTES). Read-only.
#
#   curl -o /tmp/ssid-count.rb https://pre-alpha.henryhaller.com/ssid-count.rb
#   cd /space/rxg/console && bin/rails runner /tmp/ssid-count.rb [MINUTES=15]

ARGV.each do |arg|
  key, value = arg.split('=', 2)
  ENV[key] ||= value if value && key.match?(/\A[A-Z][A-Z0-9_]*\z/)
end
mins = (ENV['MINUTES'] || 15).to_i

counts = WirelessClient.where('connected_clients.updated_at > ?', mins.minutes.ago)
                       .joins('LEFT JOIN wlans ON wlans.id = connected_clients.wlan_id')
                       .group('wlans.ssid')
                       .group(Arel.sql("CASE WHEN connected_clients.channel IS NULL THEN '?' " \
                                       "WHEN connected_clients.channel <= 14 THEN '2.4' ELSE '5' END"))
                       .count(Arel.sql('DISTINCT connected_clients.mac'))

by = Hash.new { |h, k| h[k] = Hash.new(0) }
counts.each { |(ssid, band), n| by[ssid || '(no WLAN)'][band] += n }

puts "Connected clients by SSID (rows refreshed in the last #{mins} min):"
puts format('  %-36s %8s %8s %8s %8s', 'SSID', '2.4 GHz', '5 GHz', 'unknown', 'total')
by.sort_by { |_, v| -v.values.sum }.each do |ssid, v|
  puts format('  %-36s %8d %8d %8d %8d', ssid.to_s[0, 36], v['2.4'], v['5'], v['?'], v.values.sum)
end
