@@ -11,8 +11,10 @@ import (
1111 "packagelock/logger"
1212 "packagelock/server"
1313 "packagelock/structs"
14+ "path/filepath"
1415 "strconv"
1516 "syscall"
17+ "text/template"
1618 "time"
1719
1820 "github.com/fsnotify/fsnotify"
@@ -129,9 +131,77 @@ func setup() {
129131 }
130132 pp .Println ("Generated certs directory" )
131133
134+ generateUnitFile ()
135+ pp .Println ("Generated Unit File" )
136+
132137 pp .Println ("Setup finished successfully!" )
133138}
134139
140+ func generateUnitFile () {
141+ // SystemdTemplate defines the systemd unit file structure
142+ const SystemdTemplate = `[Unit]
143+ Description=PackageLock Management Server
144+ After=network.target
145+
146+ [Service]
147+ ExecStart={{.ExecStart}} start
148+ Restart=always
149+ User={{.User}}
150+ Group={{.Group}}
151+
152+ [Install]
153+ WantedBy=multi-user.target
154+ `
155+
156+ // UnitFileData holds the dynamic data for the systemd unit file
157+ type UnitFileData struct {
158+ ExecStart string
159+ User string
160+ Group string
161+ }
162+
163+ // Get the current executable path
164+ execPath , err := os .Executable ()
165+ if err != nil {
166+ logger .Logger .Panicf ("failed to get executable path: %w" , err )
167+ }
168+ // Convert to an absolute path
169+ execPath , err = filepath .Abs (execPath )
170+ if err != nil {
171+ logger .Logger .Panicf ("failed to get absolute executable path: %w" , err )
172+ }
173+
174+ // Define the data to be injected into the unit file
175+ data := UnitFileData {
176+ ExecStart : execPath , // The path of the Go binary
177+ User : "your-user" , // Replace with your actual user
178+ Group : "your-group" , // Replace with your actual group
179+ }
180+
181+ // Open the systemd unit file for writing (requires sudo permission)
182+ filePath := "/etc/systemd/system/packagelock.service"
183+ file , err := os .Create (filePath )
184+ if err != nil {
185+ pp .Println ("Seems like you cant generate the Unit File..." )
186+ pp .Println ("Did you ran this with 'sudo'?🚀" )
187+ logger .Logger .Panicf ("failed to create systemd unit file: %w" , err )
188+ }
189+ defer file .Close ()
190+
191+ // Parse and execute the systemd template
192+ tmpl , err := template .New ("systemd" ).Parse (SystemdTemplate )
193+ if err != nil {
194+ logger .Logger .Panicf ("failed to parse systemd template: %w" , err )
195+ }
196+
197+ err = tmpl .Execute (file , data )
198+ if err != nil {
199+ logger .Logger .Panicf ("failed to execute template: %w" , err )
200+ }
201+
202+ pp .Printf ("Systemd unit file created at %s\n " , filePath )
203+ }
204+
135205// INFO: init is ran everytime a cobra comand gets used.
136206// It does not init the Server!
137207// It only inits cobra!
0 commit comments