# config valid only for current version of Capistrano
lock "3.9.1"

set :application, "radionotredame"
set :repo_url, "https://project_2_bot:bee-AyxVv4eA8mcAygNXjT8E@git.amphibee.fr/amphibee/radio-notre-dame/rnd-wp.git"
set :keep_releases, 3
set :composer_install_flags, '--no-dev --no-interaction --quiet --optimize-autoloader'

SSHKit.config.command_map[:fpm] = 'sudo service php7.4-fpm'
SSHKit.config.command_map[:composer] = "composer"
SSHKit.config.command_map[:npm] = "npm"

set :linked_dirs, ['web/app/cache', 'web/app/uploads', 'web/app/fonts', 'web/app/languages', 'web/app/upgrade', 'web/app/logs', 'web/app/wp-rocket-config', 'web/app/wp-grid-builder', 'web/app/wpgb']
set :linked_files, %w(.env)
set :log_level, :info

namespace :deploy do
  after :finishing, 'fpm:restart'
  after :rollback, 'fpm:restart'
end

task :build_assets do
  on roles(:app) do
    within "#{release_path}/web/app/themes/radionotredame" do
        execute :tar, "-xzf #{repo_path}/../artifacts.tar.gz"
        execute :rm, "#{repo_path}/../artifacts.tar.gz"
        execute :composer, "install --no-dev --no-interaction --quiet --optimize-autoloader"
    end
  end
end

task :update_config do
  on roles(:app) do
    execute "ln", "-s -f", "#{release_path}/web/app/mu-plugins", "#{shared_path}/web/app/mu-plugins"
  end
end

namespace :deploy do
    before :updating, :update_config
    before :updating, 'composer:install_executable'
    task :update_option_paths do
        on roles(:app) do
          within fetch(:release_path) do
            if test :wp, :core, 'is-installed'
              [:stylesheet_root, :template_root].each do |option|
                # Only change the value if it's an absolute path
                # i.e. The relative path "/themes" must remain unchanged
                # Also, the option might not be set, in which case we leave it like that
                value = capture :wp, :option, :get, option, raise_on_non_zero_exit: false
                if value != '' && value != '/themes'
                  execute :wp, :option, :set, option, fetch(:release_path).join('web/wp/wp-content/themes')
                end
              end
            end
          end
        end
    end
    after :updating, :build_assets
end

after 'deploy:publishing', 'deploy:update_option_paths'
