#
# Cookbook:: irrigate-apache
# Recipe:: vapi
#
# Copyright:: The Orchard
#
# Description: This recipe manages a sandboxed PHP 5.6 stack
# with all extensions and configuration to run Production environment.
# Deployments are managed with svn, sensitive info is served from
# encrypted data bags, and vhosts are programtically generated.
# This recipe follows Debian-style Apache snippet files and commands.

include_recipe 'irrigate-php::vapi'
include_recipe 'sudo'

if platform_family?('rhel')
  if node['platform_version'].start_with?('7')
    include_recipe 'selinux_policy::install'

    # There are extra required packages that are provided by the base
    # and/or apache-specific cookbooks. This array is purpose-specific.
    packages = %w(
      autoconf
      bzip2-devel
      freetype-devel
      gcc-c++
      glibc
      gmp-devel
      httpd-devel
      ImageMagick
      ImageMagick-devel
      libcurl-devel
      libdb4-devel
      libevent
      libjpeg-turbo
      libjpeg-turbo-devel
      libmcrypt
      libmcrypt-devel
      libmemcached
      libpng-devel
      libtiff
      libtiff-devel
      libxml2-devel
      make
      memcached
      mhash
      mhash-devel
      mod_ssl
      openssl-devel
      zip
    )

    packages.each do |name|
      package name
    end

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

    # PHP opcache configuration snippet in the Remi-sandboxed location
    template '/opt/remi/php56/root/etc/php.d/10-opcache.ini' do
      source '10-opcache.ini.erb'
      mode '0644'
      owner 'root'
      group 'root'
      notifies :restart, 'service[apache2]'
    end

    # PHP memcached configuration snippet in the Remi-sandboxed location
    template '/opt/remi/php56/root/etc/php.d/50-memcached.ini' do
      source '50-memcached.ini.erb'
      mode '0644'
      owner 'root'
      group 'root'
      notifies :restart, 'service[apache2]'
    end

    # Configure SVN repositories
    svn_password = data_bag_item('secrets', 'svn_deploy_password')
    svn_deploy_password = svn_password['password'].chomp

    # Due to a Chef regression (https://github.com/chef/chef/issues/4050),
    # we must create the destination directories for svn before checking out.
    # These directories must also be empty as the time of the checkout or the
    # resource assumes that is has run correctly and will exit with no action.

    svn_directories = %w(
      /var/www/vectorapi
    )

    svn_directories.each do |directory_name|
      directory directory_name do
        owner node['php']['deploy_user']
        group 'webdev'
        mode '0755'
        action :create
      end
    end

    subversion 'API' do
      repository 'http://svn.theorchard.com/svn/misc/vectorapi/trunk'
      revision 'HEAD'
      destination '/var/www/vectorapi'
      svn_username 'prod-deploy'
      svn_password svn_deploy_password
      user 'deploy'
      group 'webdev'
      action :checkout
    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 = "/var/www/vectorapi/#{ows_auth_key_name}"
    ows_auth_key = data_bag_item('secrets', ows_auth_key_name)
    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', 'ows_auth_shared_secret')
    secret = ows_auth_shared_secret_content['secret'].chomp
    setenv_params = Hash[
      'OWS_AUTH_PRIVATE_KEY_FILEPATH' => ows_auth_key_location,
      'OWS_AUTH_SHARED_SECRET' => secret
    ]

    # Apache will be connecting to services
    selinux_policy_boolean 'httpd_can_network_connect' do
      value true
      notifies :start, 'service[apache2]'
    end

    # And proxies should be writable
    proxies_folder = '/var/www/vectorapi/application/Proxies'
    directory proxies_folder do
      owner node['php']['deploy_user']
      group 'apache'
      mode '0775'
      action :create
    end
    selinux_policy_fcontext proxies_folder do
      secontext 'httpd_sys_rw_content_t'
      file_type 'd'
    end

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

    # Setup cron to cleanup report directory of any files older than two hours.
    cron 'temp_cleanup' do
      hour '*'
      minute '30'
      user 'root'
      command '/bin/find /tmp -type f -mmin +120 -exec rm -rf {} \; > /dev/null 2>&1'
    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['docroot_rewrites'])
          docroot_rewrites vhost_info['docroot_rewrites']
        end
        if defined?(vhost_info['directory_options'])
          directory_options vhost_info['directory_options']
        end
        allow_override vhost_info['allow_override']
        setenv vhost_info['setenv'] if defined?(vhost_info['setenv'])
        newrelic vhost_info['newrelic'] if defined?(vhost_info['newrelic'])
      end
    end
  end
end
