// SPDX-License-Identifier: AGPL-3.0-or-later package settings import ( "context" "fmt" "net/http" ) // Env holds the PocketBase settings that come from environment variables. // ApplyEnv writes them on every start, so changing an env var and restarting // is enough. Settings without an env var are left alone: the admin panel // manages them. type Env struct { AppName string // DOCWELL_APP_NAME WebURL string // DOCWELL_WEB_URL: {APP_URL} in PocketBase's auth emails MailFrom string // DOCWELL_MAIL_FROM // SMTP is applied only when SMTPHost is set. SMTPHost string SMTPPort int SMTPUsername string SMTPPassword string SMTPTLS bool // S3 is "true" (uploads go to the bucket), "false" (back to local disk) // or "" (the admin panel's Storage screen is in charge). S3 string S3Bucket string S3Endpoint string S3Region string S3AccessKey string S3Secret string S3ForcePathStyle bool } // PocketBase's placeholders on a fresh database. const ( pbPlaceholderName = "Acme" pbPlaceholderSender = "support@example.com" ) // ApplyEnv writes the environment's settings to PocketBase. func (s *Service) ApplyEnv(ctx context.Context, env Env) error { var cur struct { Meta struct { AppName string `json:"appName"` SenderAddress string `json:"senderAddress"` } `json:"meta"` } if err := s.pb.Do(ctx, http.MethodGet, "/api/settings", nil, &cur); err != nil { return fmt.Errorf("settings: read: %w", err) } appName := cur.Meta.AppName if env.AppName != "" { appName = env.AppName } else if appName == pbPlaceholderName || appName == "" { appName = "Docwell" } sender := cur.Meta.SenderAddress if env.MailFrom != "" { sender = env.MailFrom } else if sender == pbPlaceholderSender || sender == "" { sender = "no-reply@docwell.localhost" } webURL := env.WebURL if webURL == "" { webURL = "http://localhost:3000" } patch := map[string]any{ "meta": map[string]any{ "appName": appName, "appURL": webURL, "senderName": appName, "senderAddress": sender, }, } if env.SMTPHost != "" { port := env.SMTPPort if port == 0 { port = 587 } patch["smtp"] = map[string]any{ "enabled": true, "host": env.SMTPHost, "port": port, "username": env.SMTPUsername, "password": env.SMTPPassword, "tls": env.SMTPTLS, } } switch env.S3 { case "true": bucket, region := env.S3Bucket, env.S3Region if bucket == "" { bucket = "docwell" } if region == "" { region = "us-east-1" } patch["s3"] = map[string]any{ "enabled": true, "bucket": bucket, "endpoint": env.S3Endpoint, "region": region, "accessKey": env.S3AccessKey, "secret": env.S3Secret, "forcePathStyle": env.S3ForcePathStyle, } case "false": patch["s3"] = map[string]any{"enabled": false} } if err := s.pb.Do(ctx, http.MethodPatch, "/api/settings", patch, nil); err != nil { return fmt.Errorf("settings: apply environment: %w", settingsError(err)) } if env.SMTPHost != "" { if err := s.save(ctx, keySMTPPassword, env.SMTPPassword); err != nil { return fmt.Errorf("settings: store smtp password: %w", err) } } return nil }