import System
import System.Directory
import System.Posix.Directory
import System.IO.Unsafe
import System.Posix.Files
import System.FilePath
import System.Environment

readAllEntries :: DirStream -> IO [FilePath]
readAllEntries st = 
  do s <- readDirStream st
     case s of 
       [] -> return []
       _  -> do rest <- unsafeInterleaveIO $ readAllEntries st
                return (s:rest)

readChildren :: FilePath -> IO [FilePath]
readChildren p =
  do st <- getFileStatus p
     if isDirectory st 
      then unsafeInterleaveIO $ (walkDir p) 
      else return []

walkDir :: FilePath -> IO [FilePath]
walkDir path = 
  do ents <- openDirStream path >>= readAllEntries
     child <- mapM readChildren $ map join $ filter ((/=) '.'.head) ents
     return $ map join ents ++ concat child
 where join = joinPath.(++) [path].flip (:) []

rmbk :: FilePath -> IO()
rmbk a = walkDir a >>= mapM_ removeFile.filter ((==) '~'.last)

main :: IO()
main = getArgs >>= mapM_ rmbk