module Azubi.Module.Installable where
import Azubi.Core.Model
import Azubi.Module.Runable
class Installable a where
  
  installed :: a -> State
class Updatable a where
  
  uptodate :: a -> State
data Ebuild = Ebuild String
instance Installable Ebuild where
  installed (Ebuild package) = State
                               [Check "eix" ["--exact", "--nocolor", "--installed", package] (Just $ "check if package " ++ package ++ " is installed")]
                               [Run "emerge" [package] (Just $ "installing " ++ package)]
                               (Just $ "installed " ++ package) 
instance Updatable Ebuild where
  uptodate (Ebuild package) = States [AlwaysYes]
                              [ installed (Ebuild package)
                                , State
                                  [Not $ Check "eix" ["--upgrade-", "--nocolor",  package] Nothing]
                                  [Run "emerge" [package] (Just $ "upgrade " ++ package)]
                                  Nothing
                              ]
                              (Just $ "up to date " ++ package)
type RepoUrl = String
data Git = Git RepoUrl Path [GitOption]
data GitOption = Recursive
instance Installable Git where
  installed (Git repository path options) =
    State
    [FolderExists path]
    [ Run
      "git" ( [ "clone" , repository , path ] ++ (extractCloneOptions options) )
      (Just $ "cloning " ++ repository ++ " to " ++ path)]
    (Just $ "installed (git " ++ path ++ " <- " ++ repository ++ ")")
    where
      extractCloneOptions :: [GitOption] -> [String]
      extractCloneOptions [] = []
      extractCloneOptions (Recursive:xs) = "--recursive" : (extractCloneOptions xs)
instance Updatable Git where
  uptodate (Git repo path options) =
    States [AlwaysYes]
    [ installed (Git repo path options)
    , run (Always "git" ["--work-tree=" ++ path, "pull"])
    ]
    (Just $ "up to date (git " ++ path ++ " <- " ++ repo ++")")