{- Copyright 2017 Joey Hess <id@joeyh.name>
 -
 - Licensed under the GNU AGPL version 3 or higher.
 -}

module Role.Downloader where

import Types
import Log
import CmdLine
import SessionID
import Crypto
import Role.Developer

import Control.Concurrent.STM
import Control.Concurrent.STM.TMChan
import Data.Time.Clock.POSIX

run :: DownloadOpts -> IO ()
run = run' downloader . downloadUrl

downloader :: TMVar (TVar DeveloperState) -> TMChan (Message Entered) -> TMChan (MissingHashes AnyMessage) -> SessionID -> IO ()
downloader dsv _ichan ochan sid = do
	let logfile = sessionLogFile "." sid
	putStrLn $ "Starting download to " ++ logfile
	putStrLn "(Will keep downloading until the debug-me session is done.)"
	withLogger logfile $ \logger -> do
		sk <- genMySessionKey
		(st, _startoutput) <- processSessionStart sk ochan logger dsv
		go logger st
	putStrLn $ "Finished download to " ++ logfile
  where
	go logger st = do
		ts <- getPOSIXTime
		v <- atomically $ getServerMessage ochan st ts
		case v of
			Nothing -> return ()
			Just (o, msg) -> do
				_ <- logger msg
				case o of
					ProtocolError {} -> emitOutput o
					_ -> go logger st
