$LOAD_PATH.unshift "../lib"

require "uri"
require "net/http"
require "fastly"

require_relative "../tasks/docs.rb"
require_relative "../tasks/shared.rb"

task default: :www # at bottom

namespace :www do # rubocop:disable Metrics/BlockLength
  desc "Builds the middleman site"
  task :site do
    sh("bundle exec middleman build --parallel --clean --no-verbose")
    # TODO: remove:
    Verify.file("build/index.html")
    Verify.file("build/javascripts/all.js")
    Verify.file("build/stylesheets/site.css")
  end

  desc "Assemble the website site from middleman"
  task :assemble do
    # do nothing for now
  end

  desc "Builds the full site locally"
  task build: %w{www:site www:assemble}

  task :clean do
    rm_rf("build")
  end

  desc "Releases the site to gh-pages"
  task :release do
    src = File.expand_path "build"

    unless system("git diff-index --quiet HEAD --")
      warn "WARNING: You have uncommitted changes in this repository."
    end

    Dir.mktmpdir do |path|
      sh("git worktree add #{path}/gh-pages gh-pages")

      Dir.chdir "#{path}/gh-pages" do
        rm_rf Dir["*"]                # easiest way to account for removals

        cp_r Dir["#{src}/*"], "."     # copy build back
        File.write("CNAME", "origin.inspec.io") # TODO: just check this file in?

        sh "git add ."                          # add everything that changed

        sh "git status"
        if ENV["V"]
          sh "git diff --cached"
        end

        if ENV["PUSH"]
          sh "git commit -m 'website update'"
          sh "git push -u origin gh-pages"
        end
      end

      sh("git worktree remove -f #{path}/gh-pages")
    end
  end

  desc "Flush the inspec.io cache at Fastly"
  task :flush do
    api_key    = ENV["FASTLY_API_KEY"]
    service_id = ENV["FASTLY_SERVICE_ID"]

    unless api_key && service_id
      puts
      puts "WARNING: could not flush the Fastly cache for inspec.io."
      puts "Please set FASTLY_API_KEY and FASTLY_SERVICE_ID environment variables"
      puts "and run `rake www:flush`."
      puts
      next
    end

    Log.info "Flushing the Fastly cache"

    begin
      fastly_client  = Fastly.new(api_key: api_key)
      fastly_service = Fastly::Service.new({ id: service_id }, fastly_client)
      purge_result = fastly_service.purge_all
    rescue => e
      puts "ERROR: Fastly cache could not be purged: #{e.class} - #{e.message}"
      next
    end

    if purge_result["status"] == "ok"
      puts "Success! The Fastly cache is purged."
    else
      puts "ERROR: Fastly cache could not be purged: #{purge_result}"
    end
  end
end

desc "Full website release: includes docs build, site build, and then release"
task www: %w{docs www:build www:release www:flush}