157 lines
4.6 KiB
Go
157 lines
4.6 KiB
Go
// package main is the main package for the LapisDeploy program
|
|
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/akamensky/argparse"
|
|
)
|
|
|
|
// Circle emoji
|
|
var Circles = map[string]string{
|
|
"white": "⚪️ ",
|
|
"green": "🟢 ",
|
|
"yellow": "🟡 ",
|
|
"red": "🔴 ",
|
|
"orange": "🟠 ",
|
|
}
|
|
|
|
// fileExists returns whether the given file or directory exists.
|
|
func fileExists(path string) (bool, error) {
|
|
_, err := os.Stat(path)
|
|
if err == nil {
|
|
return true, nil
|
|
}
|
|
if os.IsNotExist(err) {
|
|
return false, nil
|
|
}
|
|
return false, err
|
|
}
|
|
|
|
// Create a configuration struct
|
|
var configuration = Configuration{}
|
|
|
|
// 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"])
|
|
sendInfo(fmt.Sprintf("Handling webhook for `%s`...", repository["full_name"]))
|
|
|
|
repo_name := repository["name"].(string)
|
|
|
|
site, exists, err := getSite(repo_name)
|
|
if err != nil {
|
|
sendError(errors.New(fmt.Sprintf("Failed to check if site '%s' exists: %s", repo_name, err)))
|
|
return
|
|
}
|
|
if exists {
|
|
sendInfo("Updating repository...")
|
|
if err := site.Update(); err != nil {
|
|
sendError(err)
|
|
return
|
|
}
|
|
new_site, exists, err := getSite(site.name)
|
|
if err != nil || !exists {
|
|
sendError(errors.New("Failed to update site data on a site we just updated: " + repo_name))
|
|
}
|
|
site = new_site
|
|
sendInfo("Restarting server...")
|
|
if error := site.Restart(); error != nil {
|
|
sendError(error)
|
|
return
|
|
}
|
|
} else {
|
|
sendInfo("Cloning repositiory...")
|
|
if error := CloneSite(repository["ssh_url"].(string), repo_name); error != nil {
|
|
sendError(error)
|
|
return
|
|
}
|
|
sendInfo("Starting server...")
|
|
if site, exists, err = getSite(repo_name); err != nil {
|
|
sendError(err)
|
|
return
|
|
}
|
|
if error := site.Start(); error != nil {
|
|
sendError(err)
|
|
return
|
|
}
|
|
defer sendMessage(MatrixMessage{text: "🚀 Launched for the first time!"})
|
|
}
|
|
sendMessage(MatrixMessage{text: Circles["green"] + "Deployed successfully!"})
|
|
}
|
|
|
|
// main is the starting point of the program
|
|
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
|
|
// Disable Matrix if it's disabled in either the config or specified on CLI
|
|
configuration.matrix.disabled = *disable_matrix || configuration.matrix.disabled
|
|
|
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // Webhook receiver
|
|
log.Print("Recieved request!")
|
|
var data map[string]interface{}
|
|
err := json.NewDecoder(r.Body).Decode(&data)
|
|
if err != nil {
|
|
log.Panic(err)
|
|
return
|
|
}
|
|
check_ips := []string{ // IPs of client to check against trusted_servers
|
|
strings.Split(r.RemoteAddr, ":")[0],
|
|
r.Header.Get("x-forwarded-for"),
|
|
}
|
|
found_trusted_server := false
|
|
for _, server := range configuration.trusted_servers {
|
|
if found_trusted_server {
|
|
break
|
|
}
|
|
for _, ip := range check_ips {
|
|
if ip == server {
|
|
log.Printf("Request IP matches a trusted server (%s)", ip)
|
|
go handler(data) // Run the handler
|
|
fmt.Fprint(w, "Received!")
|
|
found_trusted_server = true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if !found_trusted_server {
|
|
log.Print("Request IP doesn't match a trusted server! Dropping...")
|
|
}
|
|
})
|
|
// 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 !configuration.matrix.disabled { // 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
|
|
}
|