UseZipPacker()   ; must be at the top — compiler directive

IncludePath "Libraries"
IncludeFile "FastCGI.pbi"
CompilerIf #PB_Compiler_Debugger
	IncludeFile "WebServer.pbi"
CompilerEndIf

IncludePath "Includes"
IncludeFile "Modules.pbi"
IncludeFile "Database.pbi"
IncludeFile "General.pbi"
IncludeFile "Auth.pbi"
IncludeFile "FileSystem.pbi"
IncludeFile "AppStore.pbi"
IncludeFile "Router.pbi"

#FCGI_PORT = 9683
#DB_PATH   = "kumos.db"

Procedure RequestHandler(*Request)
	Router::Route(*Request)
EndProcedure

OpenConsole("KUMO.S Server")
UseSHA2Fingerprint()

If Not Database::Init(#DB_PATH)
	PrintN("[ERROR] Cannot open database: " + #DB_PATH)
	Input() : End 1
EndIf
PrintN("[  OK] Database ready: " + #DB_PATH)

If Database::UserCount() = 0
	Database::CreateUser("admin", "admin")
	PrintN("[INFO] Created default account: admin / admin")
	PrintN("[WARN] Change this password immediately after first login!")
EndIf

Database::FSInit()
PrintN("[  OK] Filesystem tables ready")

If FileSize("blobs") = -1
	CreateDirectory("blobs")
	PrintN("[  OK] Created blobs directory")
EndIf

AppStore::Init()   ; creates apps/ and tmp/ dirs, runs AppInit() DB migration
PrintN("[  OK] App store ready")

Global *Server = FastCGI::Open(#FCGI_PORT, @RequestHandler(), "127.0.0.1")

If Not *Server
	PrintN("[ERROR] Failed to start FastCGI server on port " + Str(#FCGI_PORT))
	Database::Close()
	Input() : End 1
EndIf

PrintN("[  OK] FastCGI listening on port " + Str(#FCGI_PORT))

CompilerIf #PB_Compiler_Debugger
	PrintN("Debug mode. Start a HTTP server on port 8080")
	*HTTP_Srv = WebServer::Open(8080, "./www", "127.0.0.1", 9683)
	If *HTTP_Srv
		WebServer::AddFcgiPrefix(*HTTP_Srv, "/api/")
		PrintN("[  OK] HTTP server ready. Visit http://localhost:8080/")
	Else
		PrintN("[ERROR] Failed to start HTTP server. Port 8080 already in use?")
	EndIf
CompilerEndIf


PrintN("")
PrintN("Press Enter to stop.")
PrintN("")

LastClean.i = Date()
Repeat
	Delay(100)
	If Date() - LastClean > 60
		Database::CleanExpiredSessions()
		LastClean = Date()
	EndIf
Until Inkey() = Chr(13)

PrintN("Shutting down...")
FastCGI::Close(*Server)
Database::Close()
PrintN("Done. Press Enter to exit.")
Input()

; IDE Options = PureBasic 6.30 (Windows - x64)
; ExecutableFormat = Console
; CursorPosition = 89
; FirstLine = 14
; Folding = -
; EnableXP
; DPIAware