#
# Cookbook:: irrigate-apache
# Recipe:: qa_public_php7_webapps
#
# Deployments are managed with git, sensitive info is served from
# encrypted data bags, and vhosts are programtically generated.
# This recipe follows Debian-style Apache snippet files and commands.

if platform_family?('rhel')
  if node['platform_version'].start_with?('7')

    # There are extra required packages that are provided by the base
    # and/or apache-specific cookbooks. This array is purpose-specific.
    packages = %w(
      epel-release
      git
      memcached
    )

    packages.each do |name|
      package name
    end

    service 'memcached' do
      supports restart: true, status: true, reload: false
      action [:enable, :start]
    end

    # Grant sudo access. Specific users and privileges are defined in roles.
    include_recipe 'sudo'

    error_file_directory = node['apache']['error_file_directory']

    directory error_file_directory do
      mode '0755'
      owner 'root'
      group 'webdev'
      recursive true
    end

    error_files = %w(
      404.html
      500.html
    )

    error_files.each do |error_file|
      cookbook_file "#{error_file_directory}/#{error_file}" do
        source error_file
        owner 'root'
        group 'webdev'
        mode '0640'
      end
    end

    apache_root_dir = '/var/www/html_qa'

    # The QA root directory
    directory apache_root_dir do
      owner 'deploy'
      group 'webdev'
      mode '0755'
      action :create
    end

    # Private key and secret specific to workstation
    # TODO: Make this conditional and automated.
    ows_auth_key_name = 'ows-auth.pem'
    ows_auth_key_location = "#{apache_root_dir}/#{ows_auth_key_name}"
    ows_auth_key = data_bag_item('secrets', 'qa-ows-auth.pem')
    pem = ows_auth_key['pem'].chomp
    file ows_auth_key_location do
      owner 'root'
      mode '0644'
      content pem
    end

    ows_auth_shared_secret_content = data_bag_item(
      'secrets', 'qa_ows_auth_shared_secret')
    secret = ows_auth_shared_secret_content['secret'].chomp
    setenv_secret_params = Hash[
      'OWS_AUTH_PRIVATE_KEY_FILEPATH' => ows_auth_key_location,
      'OWS_AUTH_SHARED_SECRET' => secret
    ]

    git 'Workstation' do
      repository 'git@github.com:/theorchard/workstation.git'
      reference 'master'
      destination "#{apache_root_dir}/workstation"
      user 'deploy'
      group 'webdev'
      action :checkout
    end

    # Since initial checkout is at the HEAD, also create public directories
    # and seed healthcheck files for load balancer.

    healthcheck_files = %W(
      #{apache_root_dir}/workstation/public/healthchk.php
    )

    healthcheck_files.each do |file_name|
      file file_name do
        content 'hello'
        owner 'deploy'
        group 'webdev'
        mode '0644'
        action :create
      end
    end

    # This is used by Workstation as a temporary thumbnail image location
    # Since the affected directories are only present after a managed
    # deployment, this effectively needs to run again after switching svn tags.
    public_image_dir = "#{apache_root_dir}/workstation/public/images/"
    if Dir[public_image_dir].empty?
      puts "#{public_image_dir} is empty. Deployment has not taken place."
    else
      Dir.entries(public_image_dir).each do |file|
        next unless file =~ /^coverart|^lg_coverart/
        directory public_image_dir + file do
          owner 'deploy'
          group 'webdev'
          mode '0775'
          action :create
        end
      end
    end

    # This by default references a template with a matching name
    apache_conf 'orchardphp7' do
      enable true
    end

    # Ensure the default vhost is disabled
    apache_site 'default' do
      enabled false
    end

    # Explicitly disable the default site if it is active, as a failsafe.
    execute 'a2dissite default' do
      only_if do
        File.symlink?('/etc/httpd/sites-enabled/default.conf')
      end
      notifies :restart, 'service[apache2]'
    end

    # Vhost attributes are contained in roles
    node['webapps'].each do |vhost, vhost_info|
      web_app vhost do
        template 'vhost.conf.erb'
        port vhost_info['port']
        server_admin vhost_info['server_admin']
        server_name vhost_info['server_name']
        if defined?(vhost_info['server_aliases'])
          server_aliases vhost_info['server_aliases']
        end
        docroot vhost_info['docroot']
        if defined?(vhost_info['directory_options'])
          directory_options vhost_info['directory_options']
        end
        allow_override vhost_info['allow_override']
        if vhost_info['setenv_variables'] && !vhost_info['setenv_variables'].empty?
          # Optionally append additional environment variables
          params = vhost_info['setenv_variables']
          if vhost_info['setenv_use_secret_params'] == true
            params = setenv_secret_params.merge(params)
          end
          setenv params
        end
      end
    end
  end
end
