-- Git Annex Plugin
--
-- This plugin enables support for git-annex on the server-side which allows
-- for the storage of large binary files efficiently in git.
--
-- Copyright 2016-2017 Daniel Silverstone <dsilvers@digital-scurf.org>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
-- 1. Redistributions of source code must retain the above copyright
--    notice, this list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright
--    notice, this list of conditions and the following disclaimer in the
--    documentation and/or other materials provided with the distribution.
-- 3. Neither the name of the author nor the names of their contributors
--    may be used to endorse or promote products derived from this software
--    without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-- OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.

local gitano = require "gitano"

local sp = require "luxio.subprocess"

local git_annex_short_help = "Simple git-annex command"
local git_annex_helptext = [[
Git Annex (http://git-annex.branchable.com/) is a mechanism for supporting
large files in git repositories.  This plugin relies on git-annex-shell
being available on the server, and forwards that capability on so that
if you can write to a gitano repository you can do git-annex type things
with it.  In theory if you can read from the repository then you can
still sync content from it; you just can't write to it.

This plugin is considered experimental, may not work entirely as expected,
and may change without notice.
]]

local function git_annex_detect_repo(config, parsed_cmdline)
   local repo, msg
   if #parsed_cmdline > 2 then
      -- Acquire the repository object for the target repo from arg 3
      repo, msg = gitano.repository.find(config, parsed_cmdline[3])
      if not repo then
         gitano.log.critical("Unable to locate repository.")
         gitano.log.critical("  * " .. (tostring(msg)))
         return nil, nil
      end

      if repo.is_nascent then
         gitano.log.info("Repository " .. repo.name .. " is nascent")
      end
   else
      gitano.log.critical("No repository provided.")
      return nil, nil
   end
   parsed_cmdline.__annex__repo_at = 3
   return repo, parsed_cmdline
end

local function git_annex_validate(config, repo, cmdline)
   -- All git-annex commands put the repo in cmdline[3] and all take
   -- a directory so cmdline had best be at least 3 big...
   if #cmdline < 3 then
      gitano.log.error("usage: git-annex-shell <cmd> <reponame> ...")
      return false
   end
   if repo.is_nascent then
      gitano.log.error("Cannot run git-annex-shell against a nascent repo")
      return false
   end
   return true
end

local function git_annex_prep(config, repo, cmdline, context)
   local ctxcopy = {}
   for k, v in pairs(context) do
      ctxcopy[k] = v
   end
   ctxcopy.operation = "write"
   local action, reason = repo:run_lace(ctxcopy)
   cmdline.__annex__writeable = action == "allow"
   context.operation = "read"
   return repo:run_lace(context)
end

local function git_annex_run(config, repo, cmdline, env)
   -- We need to check if we're allowed to run in write mode...
   env.GIT_ANNEX_SHELL_LIMITED = "1"
   env.GIT_ANNEX_SHELL_DIRECTORY = repo:fs_path()
   if not cmdline.__annex__writeable then
      env.GIT_ANNEX_SHELL_READONLY = "1"
   end
   local cmdcopy = {"git-annex-shell", env=env}
   for i = 2, #cmdline do cmdcopy[i] = cmdline[i] end
   cmdcopy[cmdline.__annex__repo_at] = repo:fs_path()
   local proc = sp.spawn(cmdcopy)
   return proc:wait()
end

assert(gitano.command.register("git-annex-shell",
                               git_annex_short_help, git_annex_helptext,
                               git_annex_validate, git_annex_prep, git_annex_run,
                               true, true, false, git_annex_detect_repo, true))
