#  Phusion Passenger - https://www.phusionpassenger.com/
#  Copyright (c) 2017 Phusion Holding B.V.
#
#  "Passenger", "Phusion Passenger" and "Union Station" are registered
#  trademarks of Phusion Holding B.V.
#
#  Permission is hereby granted, free of charge, to any person obtaining a copy
#  of this software and associated documentation files (the "Software"), to deal
#  in the Software without restriction, including without limitation the rights
#  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#  copies of the Software, and to permit persons to whom the Software is
#  furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#  THE SOFTWARE.

# This file uses the cxxcodebuilder API. Learn more at:
# https://github.com/phusion/cxxcodebuilder

require 'phusion_passenger/nginx/config_options'

def main
  set_indent_string '    '
  comment copyright_header_for(__FILE__), 1

  separator

  comment %q{
    MainConfig/AutoGeneratedManifestGeneration.c is automatically generated from
    MainConfig/AutoGeneratedManifestGeneration.c.cxxcodebuilder,
    using definitions from src/ruby_supportlib/phusion_passenger/nginx/config_options.rb.
    Edits to MainConfig/AutoGeneratedManifestGeneration.c will be lost.

    To update MainConfig/AutoGeneratedManifestGeneration.c:
      rake nginx

    To force regeneration of MainConfig/AutoGeneratedManifestGeneration.c:
      rm -f src/nginx_module/MainConfig/AutoGeneratedManifestGeneration.c
      rake src/nginx_module/MainConfig/AutoGeneratedManifestGeneration.c
  }

  separator

  add_code %Q{
    #include "../ConfigGeneral/ManifestGeneration.h"
  }

  separator

  function('static void generate_config_manifest_for_autogenerated_main_conf(' \
    'manifest_gen_ctx_t *ctx, passenger_main_conf_t *conf)') \
  do
    add_code %Q{
      PsgJsonValue *option_container, *hierarchy_member;
    }

    separator

    filter_eligible_options(NGINX_CONFIGURATION_OPTIONS).each do |option|
      next if !option.fetch(:auto_generate_nginx_tracking_code, true)

      source_location_struct_field = source_location_struct_field_for(option)

      add_code %Q[
        if (conf->#{source_location_struct_field}_explicitly_set) {
          option_container = find_or_create_manifest_option_container(ctx,
            ctx->global_config_container,
            #{option[:name].inspect},
            sizeof(#{option[:name].inspect}) - 1);
          hierarchy_member = add_manifest_option_container_hierarchy_member(option_container,
            &conf->#{source_location_struct_field}_source_file,
            conf->#{source_location_struct_field}_source_line);
      ]
      indent do
        add_tracking_value_serialization_code(option)
      end
      add_code %Q[
        }
      ]
    end

    separator

    skipped_options = []
    filter_eligible_options(NGINX_CONFIGURATION_OPTIONS).each do |option|
      if !option.fetch(:auto_generate_nginx_tracking_code, true)
        skipped_options << option[:name]
      end
    end
    skipped_options = ["(none)"] if skipped_options.empty?
    comment "No autogenerated code for:\n#{skipped_options.join("\n")}"
  end
end

def filter_eligible_options(options)
  options.reject do |option|
    option[:alias_for] ||
      option.fetch(:field, true).nil? ||
      option[:struct] != 'NGX_HTTP_MAIN_CONF_OFFSET'
  end
end

def value_struct_field_for(option)
  if option.key?(:field)
    result = option[:field].to_s
  else
    result = option[:name].sub(/^passenger_/, '')
  end
  if result !~ /\./
    result = "autogenerated.#{result}"
  end
  result
end

def source_location_struct_field_for(option)
  if option.key?(:field)
    result = option[:field].to_s
  else
    result = option[:name].sub(/^passenger_/, '')
  end
  result = result.gsub('.', '_')
  "autogenerated.#{result}"
end

def add_tracking_value_serialization_code(option)
  value_struct_field = value_struct_field_for(option)

  case option[:type]
  when :string
    add_code %Q{
      psg_json_value_set_str(hierarchy_member, "value",
        (const char *) conf->#{value_struct_field}.data,
        conf->#{value_struct_field}.len);
    }
  when :integer
    add_code %Q{
      psg_json_value_set_int(hierarchy_member, "value",
        conf->#{value_struct_field});
    }
  when :uinteger, :msec
    add_code %Q{
      psg_json_value_set_uint(hierarchy_member, "value",
        conf->#{value_struct_field});
    }
  when :flag
    add_code %Q{
      psg_json_value_set_bool(hierarchy_member, "value",
        conf->#{value_struct_field});
    }
  when :string_array
    add_code %Q{
      psg_json_value_set_str_array(hierarchy_member, "value",
        conf->#{value_struct_field});
    }
  when :string_keyval
    add_code %Q{
      psg_json_value_set_str_keyval(hierarchy_member, "value",
        conf->#{value_struct_field});
    }
  else
    raise "Unknown option type #{option[:type].inspect} for option #{option[:name]}"
  end
end

main
