#
# Cookbook Name:: lxcs
# Recipe:: lxc
#
# Copyright 2017, whitestar
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

lxd_conf = node['lxcs']['lxd']

directory '/etc/lxd' do
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

pkgs = [
  'lxd',
  'lxd-client',
]
if lxd_conf['with_zfs'] || \
  (lxd_conf['init']['enabled'] && lxd_conf['init']['options'] =~ /--storage-backend\s+zfs/)
  pkgs.push('zfsutils-linux') 
end

pkgs.each {|pkg|
  resources(package: pkg) rescue package pkg do
    action :install
  end
}

users = lxd_conf['users_allow']
group 'lxd' do
  members users unless users.empty?
  action :create
  append true
end

if lxd_conf['init']['enabled']
  sensitive_init = false
  opts = lxd_conf['init']['options']
  item_conf = lxd_conf['init']['trust_password_vault_item']

  unless item_conf.empty?
    sensitive_init = true
    require 'chef-vault'
    secret = ChefVault::Item.load(item_conf['vault'], item_conf['name'])
    if item_conf.key?('env_context') && item_conf['env_context'] == true
      secret = secret[node.chef_environment]
    end
    if !item_conf['key'].nil? && !item_conf['key'].empty?
      item_conf['key'].split('/').each {|elm|
        secret = secret[elm]
      }
    end

    opts += " --trust-password #{secret}"
  end

  init_command = "lxd init --auto #{opts}"
  log "lxd init command: #{init_command}" unless sensitive_init
  execute 'lxd_init' do
    command init_command
    action :nothing
    sensitive true if sensitive_init
  end

  lxd_init_command_file = '/etc/lxd/lxd_init_command_by_chef'
  file lxd_init_command_file do
    content "#{init_command}\n"  # prevent noeol
    owner 'root'
    group 'root'
    mode (sensitive_init ? '0600' : '0644')
    # do nothing first.
    action :nothing unless File.exist?(lxd_init_command_file) 
    sensitive true if sensitive_init
    # each time update is inactive at the moment.
    #notifies :run, 'execute[lxd_init]', :immediately
  end

  log 'lxd_init_only_once' do
    # do initially only once.
    only_if { !File.exist?(lxd_init_command_file) }  
    notifies :run, 'execute[lxd_init]', :immediately
    notifies :create, "file[#{lxd_init_command_file}]", :immediately
  end

  log 'lxd_init_force' do
    only_if { lxd_conf['init']['force'] }
    notifies :run, 'execute[lxd_init]', :immediately
  end
end

platfrom_version = node['platform_version']
if platfrom_version >= '16.10'
  lxd_conf['network'].each {|net_name, hash|
    require 'yaml'
    net_hash = hash.to_hash
    net_hash['name'] = net_name
    net_yaml = net_hash.to_yaml
    log "lxd network config: #{net_yaml}"

    opts = []
    hash['config'].each {|key, value|
      opts.push("#{key}=#{value}")
    }
    opts.push('--force-local')

    # create initially only once.
    execute "lxc_network_create_#{net_name}" do
      command "lxc network create #{net_name} #{opts.join(' ')}"
      action :run
      not_if "lxc network list | grep #{net_name}"
    end

    net_yaml_file = "/etc/lxd/#{net_name}_by_chef.yml"
    net_edit_exec_name = "lxc_network_edit_#{net_name}"

    execute net_edit_exec_name do
      command "cat #{net_yaml_file} | lxc network edit #{net_name}"
      action :nothing
      only_if "lxc network list | grep #{net_name}"
    end

    file net_yaml_file do
      content "#{net_yaml}\n"  # prevent noeol
      owner 'root'
      group 'root'
      mode '0644'
      action :create
      notifies :run, "execute[#{net_edit_exec_name}]", :immediately if lxd_conf['network_force_update']
    end
  }
elsif platfrom_version <= '16.04'
  if lxd_conf['bridge']['enabled']
    service 'lxd-bridge' do
      action :enable
    end

    template '/etc/default/lxd-bridge' do
      source  'etc/default/lxd-bridge'
      owner 'root'
      group 'root'
      mode '0644'
      notifies :restart, 'service[lxd-bridge]'
    end
  end
end
