forked from deploymenttheory/go-api-sdk-jamfpro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FormatMacOSConfigurationProfiles.go
219 lines (188 loc) · 6.68 KB
/
FormatMacOSConfigurationProfiles.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package main
import (
"fmt"
"html"
"os"
"path/filepath"
"strings"
"howett.net/plist"
)
// FormatMacOSConfigurationProfiles walks through the specified source directory,
// processes each .mobileconfig file by formatting its XML content, and saves the
// formatted files to the specified destination directory with an added suffix.
// This function prompts the user to input the source directory, destination directory,
// and file suffix for the processed files.
func main() {
var sourceDir, destDir, suffix string
fmt.Print("Enter the source directory where your existing configuration profiles exist: \n")
fmt.Scan(&sourceDir)
fmt.Print("Enter the destination directory where you want to save the formatted configuration profiles: \n")
fmt.Scan(&destDir)
fmt.Print("Enter a file suffix if you wish to add one: \n")
fmt.Scan(&suffix)
err := filepath.Walk(sourceDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasSuffix(path, ".mobileconfig") {
processMacOSConfigurationProfileFile(path, destDir, suffix)
}
return nil
})
if err != nil {
fmt.Println("Error processing files:", err)
return
}
fmt.Println("Processing completed.")
}
// processMacOSConfigurationProfileFile takes the path of a .mobileconfig file, reads its content,
// and formats the XML structure. The formatted XML content is then saved to a new file in the
// specified destination directory, optionally appending a suffix to the file name.
// This function is called for each .mobileconfig file found in the source directory by
// FormatMacOSConfigurationProfiles.
//
// Args:
// path (string): The file path of the .mobileconfig file to be processed.
// destDir (string): The destination directory where the formatted file will be saved.
// suffix (string): An optional suffix to be added to the file name of the formatted file.
//
// The function reads the XML content from the specified file, unmarshals it to ensure
// proper XML structure, and then marshals it back with proper indentation. The result
// is written to a new file in the destination directory with the appropriate suffix.
func processMacOSConfigurationProfileFile(path, destDir, suffix string) {
fmt.Println("Processing:", path)
// Read the file content
data, err := os.ReadFile(path)
if err != nil {
fmt.Println("Error reading file:", err)
return
}
// Check if data is empty
if len(data) == 0 {
fmt.Println("Empty file, skipping:", path)
return
}
// Decode HTML entities
decodedData := html.UnescapeString(string(data))
// Unmarshal the plist content
var plistData interface{}
_, err = plist.Unmarshal([]byte(decodedData), &plistData)
if err != nil {
fmt.Println("Error unmarshalling plist:", err)
return
}
// Call to reformatPlistData
reformattedData, err := reformatPlistData(plistData)
if err != nil {
fmt.Println("Error in reformatting plist data:", err)
return
}
// Marshal back to bytes with indentation
prettyPlist, err := plist.MarshalIndent(reformattedData, plist.XMLFormat, "\t")
if err != nil {
fmt.Println("Error marshalling plist:", err)
return
}
// Define the new file path
filename := filepath.Base(path)
newPath := filepath.Join(destDir, strings.TrimSuffix(filename, ".mobileconfig")+suffix+".mobileconfig")
// Write the formatted data to the new file
err = os.WriteFile(newPath, prettyPlist, 0644)
if err != nil {
fmt.Println("Error writing file:", err)
return
}
fmt.Println("Processed and saved:", newPath)
}
// debugLog prints debug messages if debugging is enabled.
// This can be controlled by a debug flag in production code.
func debugLog(message string) {
fmt.Println("DEBUG:", message)
}
// reformatPlistData takes the original plist data and reformats it
// into the desired structure. It handles key-value pairs, dict, and array elements.
func reformatPlistData(originalData interface{}) (interface{}, error) {
debugLog("Reformatting plist data")
// Check if the original data is a dictionary
if dict, ok := originalData.(map[string]interface{}); ok {
newDict := make(map[string]interface{})
for key, value := range dict {
switch element := value.(type) {
case []interface{}:
// Process array elements
newArray := make([]interface{}, 0)
for _, item := range element {
if itemDict, ok := item.(map[string]interface{}); ok {
// Process each dictionary in the array
newItemDict := processDict(itemDict)
newArray = append(newArray, newItemDict)
} else {
newArray = append(newArray, item)
}
}
newDict[key] = newArray
case map[string]interface{}:
// Process nested dictionary
newDict[key] = processDict(element)
default:
// Handle other types
newDict[key] = element
}
}
return newDict, nil
}
return nil, fmt.Errorf("unexpected data format")
}
// processDict applies specific transformations to a dictionary element.
func processDict(dict map[string]interface{}) map[string]interface{} {
newDict := make(map[string]interface{})
for k, v := range dict {
// Process 'PayloadContent' key specifically
if k == "PayloadContent" {
newPayloadContent := processPayloadContent(v)
newDict[k] = newPayloadContent
} else {
// Copy other keys and values as is
newDict[k] = v
}
}
return newDict
}
// processPayloadContent processes the 'PayloadContent' section of the plist.
func processPayloadContent(value interface{}) interface{} {
if array, ok := value.([]interface{}); ok {
newArray := make([]interface{}, 0)
for _, item := range array {
if itemDict, ok := item.(map[string]interface{}); ok {
// Process each dictionary in the array
newItemDict := processPayloadItem(itemDict)
newArray = append(newArray, newItemDict)
}
}
return newArray
}
return value
}
// processPayloadItem processes each item in the 'PayloadContent' array.
func processPayloadItem(dict map[string]interface{}) map[string]interface{} {
newItemDict := make(map[string]interface{})
// Add necessary keys with default values if they are missing
necessaryKeys := []string{"PayloadDescription", "PayloadDisplayName", "PayloadEnabled", "PayloadIdentifier", "PayloadOrganization", "PayloadType", "PayloadUUID", "PayloadVersion"}
for _, key := range necessaryKeys {
if _, exists := dict[key]; !exists {
switch key {
case "PayloadDescription", "PayloadDisplayName", "PayloadIdentifier", "PayloadOrganization", "PayloadType", "PayloadUUID":
newItemDict[key] = ""
case "PayloadEnabled":
newItemDict[key] = true // Assuming default is true, adjust as needed
case "PayloadVersion":
newItemDict[key] = 1 // Assuming default version is 1, adjust as needed
}
}
}
// Copy existing keys and values
for k, v := range dict {
newItemDict[k] = v
}
return newItemDict
}