require 'capistrano/sozo_magento2/info'

include SozoMagento2::Info

namespace :sozo do

desc "Info"
task :info do
    on roles(:all) do
        SozoMagento2::Info::Info.new.call
    end
end

namespace :git do
    desc "Git branch Check"
    task :check do
        on roles(:all) do
            check = capture(:git, 'ls-remote', '--heads', fetch(:repo_url), fetch(:branch), '|', 'wc', '-l')

            if check.to_i == 1
                info "Branch is available for deployment."
            else
                error "Branch does not exist in git repository, have you pushed your changes?"
                exit 1
            end
        end
    end
end

desc "Fix current directory if needed"
task :fix_current do
    on roles(:all) do
        releases = capture(:ls, "-x", releases_path).split
        valid, invalid = releases.partition { |e| /^\d{14}$/ =~ e }

        info "Checking current and magento root directories are setup correctly."

        current = "#{fetch(:deploy_to)}/current"
        if test("[ ! -e #{current} ]")
            info "Current link #{current} link is broken, regenerating."
            execute :ln, "-sf", "#{fetch(:deploy_to)}/releases/#{valid.last}", current
        end

        m2root = "#{fetch(:mage_root)}"
        if test("[ ! -e #{m2root} ]")
            info "M2Path link #{m2root} link is broken, regenerating."
            execute :ln, "-sf", "#{fetch(:deploy_to)}/releases/#{valid.last}/magento", m2root
        end
    end
end

desc "Move database connection files into place"
task :db_conn do
    on roles(:all) do
        within release_path do
            execute :cp, "#{release_path}/environments/#{fetch(:environment)}/app/etc/env.php", "#{release_path}/magento/app/etc/"
        end
    end
end

desc "Symlink the deployment to live"
task :symlink do
    on roles :all do |host|
        within release_path do
            execute :rm, "-rf", "#{fetch(:mage_root)}", "&&", "ln", "-s", "#{release_path}/magento/", "#{fetch(:mage_root)}"

            # Setup uploads
            execute :ln, "-s", "#{fetch(:deploy_to)}/shared/magento/wp/wp-content/uploads", "#{release_path}/magento/wp/wp-content"

            # Sitemap
            execute :ln, "-sf", "#{fetch(:deploy_to)}/shared/magento/sitemap/", "#{release_path}/magento/"
            execute :ln, "-sf", "#{fetch(:deploy_to)}/shared/magento/sitemap/", "#{release_path}/magento/pub/"
        end
    end

    on roles :all do |host|
        execute :ln, "-s", "#{fetch(:deploy_to)}/shared/magento/pub/.well-known", "#{release_path}/magento/pub/.well-known"
    end

    invoke! "sozo:fix_current"
end

desc "Production tasks"
task :optimise do
    on roles :all do |host|
        within release_path do
            execute :rm, "-rf", "{.git*,*.sample,.ruby-version,*.md,Capfile,Gemfile*,deployment,dev,development,magento/*.sample}"

            invoke!('provision:permissions')
        end
    end
    on roles :production do
        within release_path do
            invoke 'magento:cache:flush'
            invoke 'magento:indexer:reindex'
        end
    end
end

namespace :config do
    desc "Config file updates"
    task :setup do
        on roles(:all) do
            within release_path do
                execute :cp, "#{release_path}/environments/#{fetch(:environment)}/pub/robots.txt", "#{release_path}/magento/pub/"
                execute :cp, "#{release_path}/environments/#{fetch(:environment)}/app/etc/env.php", "#{release_path}/magento/app/etc/"
                execute :cp, "#{release_path}/environments/#{fetch(:environment)}/pub/errors/local.xml", "#{release_path}/magento/pub/errors/"
                execute :cp, "#{release_path}/environments/#{fetch(:environment)}/wp/wp-config.php", "#{release_path}/magento/wp/wp-config.php"
            end
        end
        on roles(:staging) do
            within release_path do
                execute :cp, "#{release_path}/environments/#{fetch(:environment)}/.htpasswd", "#{release_path}/magento/.htpasswd"
            end
        end

        invoke! "sozo:fix_current"
    end

    desc "Git Check"
    task :git do
        run_locally do
            git = capture('git rev-parse HEAD')
            last = capture('git rev-parse HEAD~1')
        end
    end
end

desc "Check to see if the setup directory has content"
task :setup_check do
    on roles(:all) do
        f = "#{fetch(:deploy_to)}/.setup"

        within release_path do
            if test("[ -f #{f} ]")
                info "First Deploy File Exists"
                set :first_deploy, 1
            end
        end
    end
end

desc 'Upload linked files and directories'
task :upload do
    invoke 'sozo:upload:dirs'
    invoke 'sozo:upload:files'
end

task :upload_files do
    invoke 'sozo:upload:files'
end

task :upload_dirs do
    invoke 'sozo:upload:dirs'
end

namespace :upload do

    task :files do
        on roles :app do
            fetch(:linked_files, []).each do |file|
                upload! "#{file}", "#{shared_path}/#{file}"
            end
        end
    end

    task :dirs do
        on roles :app do
            fetch(:linked_dirs, []).each do |dir|
                info "DIR: #{dir}"
                upload! "#{dir}", "#{shared_path}/", recursive: true
            end
        end
    end

end

before 'sozo:upload', 'deploy:check:make_linked_dirs'

end