#
# Cookbook:: irrigate-ciscat
# Recipe:: mysql_import
#
# Copyright:: 2018, The Orchard, All Rights Reserved.

include_recipe 'yum-mysql-community::mysql57'

# Configure the MySQL client.
mysql_client 'default' do
  action :create
end

mysql_credentials = data_bag_item('secrets', node['ciscat']['mysql_credentials_data_bag'])
mysql_user = mysql_credentials['mysql_user'].chomp
mysql_password = mysql_credentials['mysql_password'].chomp
mysql_host = mysql_credentials['mysql_host'].chomp
mysql_import_file = node['ciscat']['s3_sql_file_name']

s3_file "/tmp/#{mysql_import_file}" do
  bucket node['ciscat']['s3_bucket_name']
  remote_path node['ciscat']['s3_sql_file_path']
  owner 'root'
  group 'root'
  mode '0644'
  action :create
end

execute 'restore_database' do
  user 'root'
  command "mysql -h #{mysql_host} -u #{mysql_user} -p#{mysql_password} -D #{node['mysql']['mysql_database']} < /tmp/#{mysql_import_file}"
  notifies :create, 'ruby_block[mysql_import_flag]', :immediately
  not_if { node.attribute?('restore_database_complete') }
end

ruby_block 'mysql_import_flag' do
  block do
    node.default['restore_database_complete'] = true
    node.save
  end
  action :nothing
end
