namespace :deploy do
  namespace :symlink do
    after :linked_files, :linked_pixtech_assets

    desc "Symlink pixtech assets if exists"
    task :linked_pixtech_assets do
      next unless any? :pixtech_assets_path
      next unless any? :linked_pixtech_assets
      on release_roles :all do
        execute :mkdir, "-p", linked_pixtech_asset_dirs(release_path)

        pixtech_assets_path = Pathname(fetch(:pixtech_assets_path))
        fetch(:linked_pixtech_assets).each do |file|
          target = release_path.join(file)
          source = pixtech_assets_path.join(file)
          next unless test "[ -f #{source} ]"
          next if test "[ -L #{target} ]"
          execute :rm, target if test "[ -f #{target} ]"
          execute :ln, "-s", source, target
        end
      end
    end
  end
end

module Capistrano
  module DSL
    module Paths
      def linked_pixtech_assets(parent)
        paths = fetch(:linked_pixtech_assets)
        join_paths(parent, paths)
      end

      def linked_pixtech_asset_dirs(parent)
        map_dirnames(linked_pixtech_assets(parent))
      end
    end
  end
end
