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

unless `which heroku` =~ /heroku/
  puts "It looks like the heroku command line tool hasn't been installed yet.  Please install"
  puts "the Heroku Toolbelt from https://toolbelt.heroku.com, run 'heroku auth:login', and then"
  puts "run this script again."
  exit 1
end

def grab_heroku_config!
  grab_config_with_cmd!("heroku config -s", no_stderr: true)
end

def set_env(key, value)
  capture("heroku config:set #{key}=#{value}")
end

def check_login!
  unless File.exist?(File.expand_path("~/.netrc")) && File.read(File.expand_path("~/.netrc")) =~ /heroku/
    puts "It looks like you need to log in to Heroku.  Please run 'heroku auth:login' before continuing."
    exit 1
  end

  puts "Welcome #{`heroku auth:whoami`.strip}!  It looks like you're logged into Heroku."
  puts
end

check_login!

info = capture("heroku info")
if info =~ /Incomplete credentials detected/i
  puts info
  puts
  puts "When this is resolved, please run 'bin/setup_heroku' again."
  exit
elsif info =~ /No app specified/i
  puts "It looks like you don't have a Heroku app set up yet for this repo."
  puts "You can either exit now and run 'heroku create', or I can do it for you."
  if yes?("Would you like me to create a Heroku app for you now in this repo?")
    puts `heroku create --stack heroku-22`
    info = capture("heroku info")
  else
    puts "Okay, exiting so you can do it."
    exit 0
  end
end

if (root_id = `git rev-list --max-parents=0 HEAD`.chomp) != '620acffa5a302c6a27165d3214cf3da6be6c1d0d'
  if (`git remote`.split - %w[heroku]).empty?
    puts "You don't seem to have huginn/huginn set up as upstream repository."
    if yes?("Would you like me to set this working tree up for you?", default: :yes)
      if system('git remote add origin https://github.com/huginn/huginn.git') &&
        system('git remote update origin')
        rebase_command = "git rebase #{root_id} --onto origin/master"
        if system(rebase_command)
          puts "Done!"
        else
          system('git rebase --abort')
          puts "Rebasing your working tree onto the upstream master failed."
          puts "Please run the following command and merge your local changes by yourself."
          puts "\t#{rebase_command}"
          exit 1
        end
      else
        exit 1
      end
    end
  end
end

app_name = info.scan(/https?:\/\/([\w\d-]+)\.herokuapp\.com/).flatten.first
confirm_app_name app_name
grab_heroku_config!
print_config
set_defaults!

unless $config['DOMAIN']
  set_value 'DOMAIN', "#{app_name}.herokuapp.com", force: false
  first_time = true
end

set_value 'BUILDPACK_URL', "https://github.com/heroku/heroku-buildpack-multi.git"
set_value 'PROCFILE_PATH', "deployment/heroku/Procfile.heroku", force: false
set_value 'ON_HEROKU', "true"

unless $config['DATABASE_URL']
  puts "Setting up the postgres addon"
  puts capture("heroku addons:add heroku-postgresql")
  puts
end

unless $config['SMTP_DOMAIN'] && $config['SMTP_USER_NAME'] && $config['SMTP_PASSWORD'] && $config['SMTP_SERVER'] && $config['EMAIL_FROM_ADDRESS']
  puts "Okay, let's setup outgoing email settings.  The simplest solution is to use the free sendgrid Heroku addon."
  puts "If you'd like to use your own server, or your Gmail account, please see .env.example and set"
  puts "SMTP_DOMAIN, SMTP_USER_NAME, SMTP_PASSWORD, and SMTP_SERVER with 'heroku config:set'."
  if yes?("Should I enable the free sendgrid addon?")
    puts capture("heroku addons:add sendgrid")

    set_value 'SMTP_SERVER', "smtp.sendgrid.net", silent: true
    set_value 'SMTP_DOMAIN', "heroku.com", silent: true

    grab_heroku_config!
    set_value 'SMTP_USER_NAME', $config['SENDGRID_USERNAME'], silent: true
    set_value 'SMTP_PASSWORD', $config['SENDGRID_PASSWORD'], silent: true
  else
    puts "Okay, you'll need to set SMTP_DOMAIN, SMTP_USER_NAME, SMTP_PASSWORD, and SMTP_SERVER with 'heroku config:set' manually."
  end

  unless $config['EMAIL_FROM_ADDRESS']
    email = nag("What email address would you like email to appear to be sent from?")
    set_value 'EMAIL_FROM_ADDRESS', email
  end
end

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

  puts "Running database migrations..."
  puts capture("heroku run rake db:migrate")
end

if first_time
  puts "Restarting..."
  puts capture("heroku restart")
  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("heroku run rake db:seed SEED_EMAIL=#{Shellwords.escape Shellwords.escape(seed_email)} SEED_USERNAME=#{Shellwords.escape Shellwords.escape(seed_username)} SEED_PASSWORD=#{Shellwords.escape Shellwords.escape(seed_password)}")
      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 https://#{app_name}.herokuapp.com and login as '#{seed_username}' with your password."
    puts
    puts "If you'd like to make more users, you can visit https://#{app_name}.herokuapp.com/users/sign_up and use the invitation code:"
  else
    puts
    puts "Visit https://#{app_name}.herokuapp.com/users/sign_up and use the invitation code shown below:"
  end
  puts
  puts "\t#{$config['INVITATION_CODE']}"
  puts
  puts "We strongly recommend that you read https://github.com/huginn/huginn/blob/master/doc/heroku/install.md thoroughly!"
end

puts
puts "Done!"
