{-# OPTIONS -cpp -fffi #-}
--
-- Wrapper for using cygwin/msys scp with darcs on Windows.
-- Use as follows:
--	- compile with 'ghc --make scpwrap.hs -o scpwrap'
--	- set the environment variable DARCS_SCP=/path/to/scpwrap.exe
--	- if scp is not in your path, set REAL_DARCS_SCP to point to it
--	- the script tries to detect whether you're using msys or cygwin:
--	  if scp is found along a path that contains "msys", then it assumes
--	  msys, otherwise cygwin.  If this is wrong, then you'll have to 
--	  modify the script.
--
import System.Environment
import System.Process
import System.Exit
import Foreign
import Foreign.C
import System.Directory
import Data.List
import System.IO
import System.IO.Error	( try )

main = do
  args <- getArgs
  m_real_scp <- try (getEnv "REAL_DARCS_SCP")
  real_scp <- 
	case m_real_scp of
	  Right f  -> return f
	  _ -> do m <- findExecutable "scp"
		  case m of
		     Just f  -> return f
		     Nothing -> do hPutStrLn stderr "can't find scp on PATH"
				   exitWith (ExitFailure 1)
  let is_msys = any ("msys" `isPrefixOf`) (tails real_scp)
  putStrLn (unwords (real_scp : map (translate is_msys) args))
  p <- runProcess real_scp (map (translate is_msys) args) 
			Nothing Nothing Nothing Nothing Nothing
  waitForProcess p >>= exitWith

translate :: Bool -> String -> String
translate is_msys (d:':':sep:rest)
   | isPathSeparator sep = if is_msys then '/':d:sep:rest
				      else "/cygdrive/" ++ d:sep:rest
translate _ arg = arg

isPathSeparator :: Char -> Bool
isPathSeparator ch = ch == '/' || ch == '\\'
