#
# Copyright:: Copyright (c) 2017 GitLab Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# For testing purposes, if the first path cannot be found load the second
begin
  require_relative '../../cookbooks/package/libraries/deprecations'
rescue LoadError
  require_relative '../gitlab-cookbooks/package/libraries/deprecations'
end
require 'json'
require_relative "lib/gitlab_ctl/util"

add_command 'check-config', 'Check if there are any configuration in gitlab.rb that is removed in specified version', 2 do |cmd_name|
  # Extracting JSON from the fqdn.json file generated by reconfigure.
  # Since we can't have fqdn info here, we do a glob and choose the first json
  # file. Reconfigure removes existing json file before creating a new one, so
  # it is safe enough.
  node_json_file = Dir.glob("#{base_path}/embedded/nodes/*.json")[0]
  unless node_json_file
    log "JSON file with existing configuration not found inside #{base_path}/embedded/nodes."
    log "Skipping config check."
    Kernel.exit 0
  end

  if GitlabCtl::Util.public_attributes_broken?
    log 'Public attributes file is missing, run gitlab-ctl reconfigure to re-create it.'
    Kernel.exit 1
  end

  node_json = JSON.load_file(node_json_file)
  unless node_json.key?("normal")
    log "Malformed configuration JSON file found at #{node_json_file}."
    log "This usually happens when your last run of `gitlab-ctl reconfigure` didn't complete successfully."
    log "This file is used to check if any of the unsupported configurations are enabled,"
    log "and hence require a working reconfigure before upgrading."
    log "Please run `sudo gitlab-ctl reconfigure` to fix it and try again."
    Kernel.exit 1
  end
  existing_config = node_json['normal']

  opts = parse_opts
  messages = Gitlab::Deprecations.check_config(opts[:version], existing_config, :removal)
  Kernel.exit 0 if messages.empty?

  log messages.join("\n")
  log 'Deprecations found. Please correct them and try again.'
  Kernel.exit opts[:fail_exit_code]
end

def parse_opts
  options = { fail_exit_code: 1 }

  OptionParser.new do |opts|
    opts.on('-vVER', '--version=VER', 'Version to be installed') do |version|
      options[:version] = version
    end
    opts.on('-n', '--no-fail', 'Show deprecation warnings but do not exit with error code') do
      options[:fail_exit_code] = 0
    end
  end.parse!(ARGV)

  options
end
