#!/usr/bin/env ruby
# Sync data for apps from GitHub

require "bundler/setup"
require "open-uri"
require "octokit"
require "yaml"
client = Octokit::Client.new(:access_token => ENV["GH_TOKEN"])

files = ARGV[0] ? [ARGV[0]] : Dir.glob('_apps/*.md')

files.each do |path|
  app = YAML.load_file(path)
  puts "Syncing #{app['repository']}"

  repo = client.repository(app['repository'])
  app['stars'] = repo[:stargazers_count]
  app['updated'] = repo[:pushed_at].to_s

  if app['host']
    begin
      stats = JSON.parse(URI(app['host'] + '/probot/stats').open.read)
      app['installations'] = stats['installations']
      app['organizations'] = stats['popular'].map { |org| org['login'] }
    rescue => e
      warn e.message
    end
  end

  content = File.read(path)
  content.sub!(/---(.*?)---/m, "#{YAML.dump(app)}---")
  File.write(path, content)
end
