#
# Cookbook:: irrigate-apache
# Recipe:: qa_public_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
      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 'API' do
      repository 'git@github.com:/theorchard/orchard.git'
      reference 'master'
      destination "#{apache_root_dir}/api"
      user 'deploy'
      group 'webdev'
      action :checkout
    end

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

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

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

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

    git 'SCC' do
      repository 'git@github.com:/theorchard/soundcloud-connect.git'
      reference 'master'
      destination "#{apache_root_dir}/scc"
      user 'deploy'
      group 'webdev'
      action :checkout
    end

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

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

    git 'Workstation' do
      repository 'git@github.com:/theorchard/orchard.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}/api/public/healthchk.php
      #{apache_root_dir}/developer/public/healthchk.php
      #{apache_root_dir}/epk/public/healthchk.php
      #{apache_root_dir}/oa/public/healthchk.php
      #{apache_root_dir}/ows-metadata/public/healthchk.php
      #{apache_root_dir}/player/public/healthchk.php
      #{apache_root_dir}/scc/public/healthchk.html
      #{apache_root_dir}/webservice/public/healthchk.php
      #{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

    # Ensure more open permissions for proxies directories
    proxies_directories = %W(
      #{apache_root_dir}/epk/application/Proxies
    )

    proxies_directories.each do |directory_name|
      directory directory_name do
        mode '0775'
        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 'qa_orchard' do
      enable true
    end

    # Firewall rules for additional Orchard vhosts
    firewall_rule 'http-81' do
      port 81
      protocol :tcp
      position 11
      command :allow
    end

    firewall_rule 'http-82' do
      port 82
      protocol :tcp
      position 12
      command :allow
    end

    firewall_rule 'http-83' do
      port 83
      protocol :tcp
      position 13
      command :allow
    end

    firewall_rule 'http-84' do
      port 84
      protocol :tcp
      position 14
      command :allow
    end

    firewall_rule 'http-85' do
      port 85
      protocol :tcp
      position 15
      command :allow
    end

    firewall_rule 'http-86' do
      port 86
      protocol :tcp
      position 16
      command :allow
    end

    firewall_rule 'http-87' do
      port 87
      protocol :tcp
      position 17
      command :allow
    end

    firewall_rule 'http-88' do
      port 88
      protocol :tcp
      position 18
      command :allow
    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
        newrelic vhost_info['newrelic'] if defined?(vhost_info['newrelic'])
      end
    end
  end
end
