LapisDeploy/main.go

135 lines
4.3 KiB
Go
Raw Normal View History

// package main is the main package for the LapisDeploy program
2024-03-07 15:11:25 -06:00
package main
2024-03-07 16:43:06 -06:00
import (
"encoding/json"
"fmt"
2024-03-14 11:50:53 -05:00
"github.com/akamensky/argparse"
2024-03-07 16:43:06 -06:00
"log"
"net/http"
"os"
2024-03-07 16:43:06 -06:00
)
2024-03-07 15:11:25 -06:00
2024-04-12 11:19:43 -05:00
// Circle emoji storage.
var Circles = map[string]string{
"white": "⚪️ ",
"green": "🟢 ",
"yellow": "🟡 ",
"red": "🔴 ",
"orange": "🟠 ",
}
// Create a configuration struct
2024-03-08 15:16:33 -06:00
var configuration = Configuration{}
// fileExists returns whether the given file or directory exists.
func fileExists(path string) (bool, error) {
2024-03-14 11:50:53 -05:00
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// handler is in charge of handling requests after the JSON has been parsed
func handler(data map[string]interface{}) {
repository := data["repository"].(map[string]interface{})
log.Default().Printf("Repo: %s", repository["full_name"])
2024-04-12 11:19:43 -05:00
sendMessage(MatrixMessage{text: fmt.Sprintf("%sHandling webhook for `%s`...",
Circles["white"], repository["full_name"])})
repo_name := repository["name"].(string)
site, exists, err := getSite(repo_name)
if err != nil {
deploy_error := newDeployError(1, "handler", fmt.Sprintf("Failed to check if site '%s' exists", repo_name), fmt.Sprint(err))
2024-03-14 11:50:53 -05:00
deploy_error.SendOverMatrix()
return
}
if exists {
2024-04-12 11:19:43 -05:00
sendMessage(MatrixMessage{text: Circles["white"] + "Updating repository..."})
if deploy_error := site.Update(); deploy_error.code != 0 {
2024-03-14 11:50:53 -05:00
deploy_error.SendOverMatrix()
return
}
new_site, exists, err := getSite(site.name)
if err != nil || !exists {
newDeployError(1, "main", "Failed to update site data on a site we just created!", fmt.Sprint(err))
}
site = new_site
2024-04-12 11:19:43 -05:00
sendMessage(MatrixMessage{text: Circles["white"] + "Restarting server..."})
if deploy_error := site.Restart(); deploy_error.code != 0 {
2024-03-14 11:50:53 -05:00
deploy_error.SendOverMatrix()
return
}
} else {
2024-04-12 11:19:43 -05:00
sendMessage(MatrixMessage{text: Circles["white"] + "Cloning repository..."})
if deploy_error := CloneSite(repository["ssh_url"].(string), repo_name); deploy_error.code != 0 {
2024-03-14 11:50:53 -05:00
deploy_error.SendOverMatrix()
return
}
2024-04-12 11:19:43 -05:00
sendMessage(MatrixMessage{text: Circles["white"] + "Starting server..."})
if site, exists, err = getSite(repo_name); err != nil {
deploy_error := newDeployError(1, "handler",
fmt.Sprintf("Failed to get site '%s' after creation!", repo_name), fmt.Sprint(err))
deploy_error.SendOverMatrix()
}
if deploy_error := site.Start(); deploy_error.code != 0 {
2024-03-14 11:50:53 -05:00
deploy_error.SendOverMatrix()
return
}
defer sendMessage(MatrixMessage{text: "🚀 Launched for the first time!"})
2024-03-10 21:22:05 -05:00
}
2024-04-12 11:19:43 -05:00
sendMessage(MatrixMessage{text: Circles["green"] + "Deployed successfully!"})
}
// main is the starting point of the program
2024-03-14 11:50:53 -05:00
func main() {
// Parse arguments
parser := argparse.NewParser("lapisdeploy", "Easily deploy Lapis web applications through Gitea webhooks")
config_path := parser.String("c", "config", &argparse.Options{Required: false, Help: "Configuration file", Default: "./config.lua"})
disable_matrix := parser.Flag("M", "disable-matrix", &argparse.Options{Required: false, Help: "Disable Matrix chat bot", Default: false})
if err := parser.Parse(os.Args); err != nil { // Parse arguments
fmt.Print(parser.Usage(err)) // Show usage if there's an error
return
}
if exists, err := fileExists(*config_path); !exists {
fmt.Printf("Invalid config file '%s'\n", *config_path)
os.Exit(1)
} else if err != nil {
panic(err)
}
parseConfig(*config_path, &configuration) // Parse JSON configuration file
2024-03-14 11:50:53 -05:00
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Webhook receiver
2024-03-07 16:43:06 -06:00
var data map[string]interface{}
err := json.NewDecoder(r.Body).Decode(&data)
if err != nil {
log.Panic(err)
2024-03-07 16:43:06 -06:00
return
}
go handler(data) // Run the handler
fmt.Fprint(w, "Received!")
2024-03-07 16:43:06 -06:00
})
// Attempt to create sites_dir
if exists, _ := fileExists(configuration.sites_dir); !exists {
os.Mkdir(configuration.sites_dir, 640) // Permissions are 640 (Owner: rw, Group: r, All: none)
}
log.Printf("Starting Lapis Deploy on port %d...", configuration.port)
startAllSites() // Start all the servers
if !*disable_matrix { // Only start Matrix bot if --disable-matrix isn't passed
go initMatrix() // Start Matrix stuff in a goroutine
} else {
log.Print("Matrix bot is disabled!")
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", configuration.port), nil)) // Start HTTP server
2024-03-07 15:11:25 -06:00
}