#!/usr/bin/env ruby
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'setup_tools'))
include SetupTools

if ARGV.length > 0
  mode = ARGV.shift
else
  mode = ''
end

unless `which rhc` =~ /rhc/
  puts "It looks like the 'rhc' command line tool hasn't been installed yet.  Please install"
  puts "it with 'gem install rhc', run 'rhc setup', and then run this script again."
  exit 1
end

def grab_openshift_config!
  grab_config_with_cmd!("rhc env list")
end

def set_env(key, value)
  capture("rhc env set #{key}=#{value}")
end

def check_login!
  token_file = Dir[File.join(File.expand_path('~/.openshift'), 'token_*')].first
  unless token_file
    puts "It looks like you need to log in to OpenShift.  Please run 'rhc setup' before continuing a choose the option to 'Generate a token now', then run bin/setup_openshift again."
    exit 1
  end

  unless (Time.now - File.stat(token_file).mtime).to_i < 60 * 60 * 24 * 5
    puts "Please run 'rhc logout' and then 'rhc account' to refresh your session, then run bin/setup_openshift again."
    exit 1
  end

  puts "Welcome #{`rhc account`.scan(/Login (.*?) on /).first.first}!  It looks like you're logged into OpenShift."
  puts
end

check_login!

info = capture("rhc app show")
just_made = false
if info =~ /must specify an application/i
  foreman_cartridge = 'http://cartreflect-claytondev.rhcloud.com/reflect?github=cantino/huginn-openshift-foreman-cartridge'
  cmd = "rhc app create huginn ruby-2.0 mysql-5.5 #{foreman_cartridge} -s -r tmp-huginn"
  puts "It looks like you don't have an OpenShift app set up yet for this repo. I can make one for you."
  if yes?("Would you like me to create an OpenShift app for you now in this repo?")
    puts "Okay, this may take a moment..."
    puts `#{cmd}`

    git_config = capture("git config --list -f tmp-huginn/.git/config").split("\n")
    git_config.grep(/^rhc\./).each do |line|
      path, value = line.split('=')
      puts `git config #{path} #{value}`
    end

    url = git_config.grep(/^remote\.origin\.url/).first.split('=').last
    puts "Adding remote #{url}"
    puts `git remote add openshift #{url}`

    puts "Removing tmp OpenShift repo"
    puts `rm -rf ./tmp-huginn`

    puts "Updating git"
    puts `git fetch openshift`

    info = capture("rhc app show")
    just_made = true
  else
    puts "Okay, exiting so you can do it."
    exit 0
  end
elsif info =~ /Application '.*?' not found/
  puts "It looks like you've deleted your OpenShift app.  If that's the case, you should"
  puts "edit .git/config and remove the sections under [rhc] and under [remote \"openshift\"]."
  exit 1
end

app_name, app_url = info.scan(/^([\w\d]+) @ https?:\/\/([^\/ ]+)/i).flatten
confirm_app_name app_name unless just_made
grab_openshift_config!
print_config
set_defaults!

first_time = mode =~ /^first/i
unless $config['DOMAIN']
  set_value 'DOMAIN', app_url, force: false
  first_time = true
end

set_value 'BUNDLE_WITHOUT', 'development:test'
puts `rhc ssh huginn 'gem install bundler'`

puts
puts "To setup outbound email, we suggest using Gmail.  See the 'Outgoing email settings' section in .env.example."
puts "You'll need to set those environment variables in OpenShift using 'rhc env set VARIABLE=VALUE'"
puts

branch = capture("git rev-parse --abbrev-ref HEAD")
if first_time || yes?("Should I push your current branch (#{branch}) to OpenShift?", default: :yes)
  puts "This may take a moment..."
  puts capture("git push openshift #{branch}:master -f")
end

if first_time
  puts "Restarting..."
  puts capture("rhc app restart")
  puts capture("rhc cartridge restart foreman")
  puts "Done!"
  puts
  puts
  puts "I can make an admin user on your new Huginn instance and setup some example Agents."
  if yes?("Should I create a new admin user and some example Agents?", default: :yes)
    done = false
    while !done
      seed_email = nag "Okay, what is your email address?"
      seed_username = nag "And what username would you like to login as?"
      seed_password = nag "Finally, what password would you like to use?", noecho: true
      puts "\nJust a moment..."

      result = capture("rhc ssh huginn 'cd $OPENSHIFT_REPO_DIR && RAILS_ENV=production bundle exec rake db:seed SEED_EMAIL=#{seed_email} SEED_USERNAME=#{seed_username} SEED_PASSWORD=#{seed_password}'")
      puts result
      if result =~ /Validation failed/
        puts "ERROR:"
        puts
        puts result
        puts
      else
        done = true
      end
    end
    puts
    puts
    puts "Okay, you should be all set!  Visit http://#{app_url} and login as '#{seed_username}' with your password."
    puts
    puts "If you'd like to make more users, you can visit http://#{app_url}/users/sign_up and use the invitation code:"
  else
    puts
    puts "Visit https://#{app_url}/users/sign_up and use the invitation code shown below:"
  end
  puts
  puts "\t#{$config['INVITATION_CODE']}"
  puts
  puts "We recommend that you read https://github.com/cantino/huginn/wiki/Run-Huginn-for-free-on-OpenShift and setup Pingdom to keep your app awake!"
end

puts
puts "Done!"
