-
Notifications
You must be signed in to change notification settings - Fork 2
/
Backup_Jamf-scripts.command
199 lines (157 loc) · 54.9 KB
/
Backup_Jamf-scripts.command
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
#!/bin/bash
#download all scripts quickly via UAPI, create CSVs of script meta-data (parameter, priority, etc...)
#debug - hold the command key down for xtrace debugging when you run this script
commandKeyDown=$(osascript -l JavaScript -e "ObjC.import('Cocoa'); ($.NSEvent.modifierFlags & $.NSEventModifierFlagCommand) > 1" 2>/dev/null)
#set xtraceFlag if /tmp/debug found or Command key is held down
[ -f /tmp/debug -o "$commandKeyDown" = "true" ] && xtraceFlag=1
[ -n "$xtraceFlag" ] && set -x
#############
# VARIABLES #
#############
#hardcode or if blank will be prompted interactively
APIURL=""
APIUSER=""
#use "-k" for test environments with self signed certs
#uncomment if needed REMEMBER -k in production IS INSECURE!
#sslOpt="-k"
######################
# COMPUTED VARIABLES #
######################
myFolderPath=$(dirname "${0}")
dateStampNow=$(date +"%Y%m%d-%H%M")
#############
# FUNCTIONS #
#############
#v0.9.5
function jpt #([options] [query] [fileArg])
{
#if xtracing quiet things down
set +x
read -r -d '' JSCode <<-'EOF'
function jsonPath(obj,expr,arg){var P={resultType:arg&&arg.resultType||"VALUE",singleQuoteKeys:arg&&arg.singleQuoteKeys||false,escapeUnicode:arg&&arg.escapeUnicode||false,result:[],normalize:function(expr){if(expr.constructor===null||expr.constructor!==String)return expr},asPath:function(path){if(P.resultType==="PATH_OBJECT")return{"path":path};var qt=P.singleQuoteKeys?"'":'"';var p=P.resultType==="PATH_JSONPOINTER"?"":"$";var x=path.slice();for(var i=0,n=x.length;i<n;i++)if(P.resultType==="PATH_JSONPOINTER")p+="/"+(x[i].constructor===Number?x[i]:x[i].replace(/~/g,"~0").replace(/\//g,"~1"));else{var pathString=x[i].constructor===Number?"["+x[i]+"]":P.resultType==="PATH_DOTTED"&&/^[A-Za-z_$][\w\d$]*$/.test(x[i])?"."+x[i]:("["+qt+(P.singleQuoteKeys?x[i].replace(/'/g,"\\'"):x[i].replace(/"/g,'\\"'))+qt+"]").replace(/\n/g,"\\n").replace(/[\b]/g,"\\b").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001f\u007f]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)});if(P.escapeUnicode)pathString=pathString.replace(/[\u007F-\uFFFF]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)});p+=pathString}return p},store:function(p,v){if(P.escapeUnicode&&v!==null&&v.constructor===String)v=v.replace(/[\u007F-\uFFFF]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)});if(p)P.result[P.result.length]=/^PATH/.test(P.resultType)?P.asPath(p):v;return!!p},trace:function(expr,val,path){if(expr===false)return expr;if(expr.length){var x=expr.slice();var loc=x.shift();if(val!==null&&Array.isArray(val)&&loc.constructor===String&&loc.match(/^0/)&&loc!=="0")throw new Error("Property name '"+loc+"' is a string with leading zeros and target is an array!");else if(val!==null&&val.constructor===Object&&loc.constructor===Number)throw new Error("Property '"+loc+"' is a number and target is an object!");if(loc.constructor===Number&&Math.sign(loc)===-1&&(val instanceof Array||val.constructor===String))loc=val.length+loc;if(Array.isArray(loc))for(i=0;i<loc.length;i++){var tx=x.slice();tx.unshift(loc[i]);P.trace(tx,val,path)}else if(loc.constructor===Object)if(Array.isArray(loc.expression))P.slice(loc.expression,x,val,path);else if(loc.expression==="*")P.walk(loc.expression,x,val,path,function(m,l,x,v,p){var tx=x.slice();tx.unshift(m);P.trace(tx,v,p)});else if(loc.expression===".."){P.trace(x,val,path);P.walk(loc,x,val,path,function(m,l,x,v,p){var tx=x.slice();tx.unshift({"expression":".."});var tp=p.slice();tp.push(m);typeof v[m]==="object"&&P.trace(tx,v[m],tp)})}else if(/^\(.*?\)$/.test(loc.expression)){var tx=x.slice();tx.unshift(P.eval(loc.expression,val,path[path.length-1]));P.trace(tx,val,path)}else if(/^-$/.test(loc.expression)){if(val!==null&&Array.isArray(val)){var tx=x.slice();tx.unshift(P.eval("(@.length)",val,path[path.length-1]));P.trace(tx,val,path)}}else{if(/^\?\(.*?\)$/.test(loc.expression))P.walk(loc.expression,x,val,path,function(m,l,x,v,p){if(P.eval(l.replace(/^\?\((.*?)\)$/,"$1"),v instanceof Array?v[m]:v,m)){var tx=x.slice();tx.unshift(m);P.trace(tx,v,p)}})}else if(val&&val[loc]!==undefined){var tpath=path.slice();tpath.push(Array.isArray(val)?Number(loc):loc);P.trace(x,val[loc],tpath)}}else P.store(path,val)},walk:function(loc,expr,val,path,f){if(val instanceof Array)for(var i=0,n=val.length;i<n;i++){if(i in val)f(i,loc,expr,val,path)}else if(typeof val==="object")for(var m in val)if(val.hasOwnProperty(m))f(m,loc,expr,val,path)},slice:function(loc,expr,val,path){if(val!==null&&val.constructor===String){val=val.split("");var isString=true}else var isString=false;if(val instanceof Array){var str="",len,start,end,step=1;loc[0]=loc[0]!==undefined?loc[0]:null;loc[1]=loc[1]!==undefined?loc[1]:null;loc[2]=loc[2]!==undefined?loc[2]:null;if((loc[2]===null||loc[2].constructor===Number?loc[2]:P.eval(loc[2].expression,val,path[path.length-1]))===0)throw new RangeError("Slice step cannot be zero: ["+loc.join(":")+"]");else step=parseInt((loc[2]===null||loc[2].constructor===Number?loc[2]:P.eval(loc[2].expression,val,path[path.length-1]))||step);if(Math.sign(step)===-1)len=val.length,start=len-1,end=(len+(loc[1]===null?1:0))*-1;else len=val.length,start=0,end=len;start=parseInt((loc[0]===null||loc[0].constructor===Number?loc[0]:P.eval(loc[0].expression,val,path[path.length-1]))||((loc[0]===null||loc[0].constructor===Number?loc[0]:P.eval(loc[0].expression,val,path[path.length-1]))===0?0:start));end=loc[1]===0?0:parseInt((loc[1]===null||loc[1].constructor===Number?loc[1]:P.eval(loc[1].expression,val,path[path.length-1]))||end);start=start<0?Math.max(Math.sign(step)===-1?-1:0,start+len):Math.min(len,start);end=end<0?Math.max(Math.sign(step)===-1?-1:0,end+len):Math.min(len,end);if(Math.sign(step)===-1)var op=">";else var op="<";for(var i=start;eval(i+op+end);i+=step)if(!isString){var texpr=expr.slice();texpr.unshift(i);P.trace(texpr,val,path)}else str+=val[i];if(isString)P.store(path,str)}},eval:function(x,_v,_vname){var tx=x.slice();if(/^\(.*?\)$/.test(x))tx=tx.replace(/^\((.*?)\)$/,"$1");var forbiddenInvocations=tx.split("").reverse().join("").replace(/(["'])(.*?)\1(?!\\)/g,"").replace(/(\/.*?\/(?!\\)\s*~=)|(=~*\s\/.*?\/(?!\\))/g,"").replace(/\(\s*/g,"(").replace(/([;\.\+\-~!\*\/%><&\^\|:\?,])/g," ").replace(/\s+/g," ").split("").reverse().join("").split(" ").filter(function(f){return/\(/.test(f)}).filter(function(f){return/[!^]\(|[\w\d_$]\(/.test(f)}).filter(function(f){return!/test\(|exec\(|match\(/.test(f)});if(forbiddenInvocations.length)throw new Error("Invocation violation: "+forbiddenInvocations);try{var evalResult=eval(x.replace(/(^|[^\\])@/g,"$1_v").replace(/\\@/g,"@").replace(/(_v(?:(?!(\|\||&&)).)*)=~((?:(?!\)* *(\|\||&&)).)*)/g,function(match,p1,p2,p3,offset,currentString){return match?p3.trim()+".test("+p1.trim()+")":match}).replace(/((?:(?!\)* *(\|\||&&)).)*)\s+=~\s+(_v(?:(?!(\|\||&&)).)*)/g,function(match,p1,p2,p3,offset,currentString){return match?p1.trim()+".test("+p3.trim()+")":match}));if(evalResult===undefined||evalResult===null||evalResult.constructor===Number&&Math.sign(evalResult)===-1)return false;else return evalResult.constructor===Number?Math.floor(evalResult):evalResult}catch(e){throw new SyntaxError("eval: "+e.message+": "+x.replace(/(^|[^\\])@/g,"$1_v").replace(/\\@/g,"@").replace(/(_v(?:(?!(\|\||&&)).)*)=~((?:(?!\)* *(\|\||&&)).)*)/g,function(match,p1,p2,p3,offset,currentString){return match?p3.trim()+".test("+p1.trim()+")":match}).replace(/((?:(?!\)* *(\|\||&&)).)*)\s+=~\s+(_v(?:(?!(\|\||&&)).)*)/g,function(match,p1,p2,p3,offset,currentString){return match?p3.trim()+".test("+p1.trim()+")":match}));}}};var $=obj;if(expr&&obj!==undefined&&(P.resultType=="VALUE"||/^PATH/.test(P.resultType))){P.trace(P.normalize(expr),obj,[]);return P.result.length?P.result:[]}}function jscChunkPrint(resultText){var breakIndex,windowEnd,startBytes=0;var totalBytes=resultText.length;var delimiters=["\n",'","','",',',"',"},{",'":"','":{'];do{if(startBytes+maxSize.print>totalBytes)windowEnd=totalBytes;else{for(i=0;i<=delimiters.length-1;i++){breakIndex=resultText.lastIndexOf(delimiters[i],startBytes+maxSize.print);if(breakIndex!==-1&&breakIndex>startBytes){windowEnd=breakIndex+delimiters[i].length-1;break}}if(breakIndex<startBytes)windowEnd=startBytes+maxSize.print}print(resultText.slice(startBytes,windowEnd));if(windowEnd===totalBytes)break;if(resultText.charAt(windowEnd)==="\n")startBytes=windowEnd+1;else startBytes=windowEnd}while(windowEnd<totalBytes)}function renderObject(obj,pathName,option,level){option=option||{};option.maxDepth=option.maxDepth===undefined||option.maxDepth<-1?-1:option.maxDepth;var keyQuotes=option.q?"'":'"';var stringQuotes=option.Q?"'":'"';var result=[];var indent="";var makeIndent=function(spaceArg,level){var indentComp="";if(spaceArg.constructor===Number)for(i=0;i<spaceArg;i++)indentComp+=" ";else indentComp=spaceArg;for(i=0;i<level;i++)indent+=indentComp;return indent};if(isNaN(level))var level=0;else level++;if(option.K&&!(option.J||option.R))option.K=false;if((option.K||option.T)&&option.i)var indent=makeIndent(option.spaceArg,level);if(obj===null){var isNull=true;obj=option.n||pathName?"null":""}var typeString=obj.constructor===Number?": Number":obj.constructor===String&&!isNull?": String":obj.constructor===Array?": Array":obj.constructor===Object?": Object":obj.constructor===Boolean?": Boolean":": null";if(obj.constructor===Array){if((option.J||option.R)&&!option.P&&(pathName||pathName===""))result.push(indent+pathName+(option.C?": Array":""));else if(!option.P&&(pathName||pathName===""))result.push(indent+pathName+(option.K?!option.C?"":typeString:level===option.maxDepth?"="+JSON.stringify(obj,null,0):"=[]"));if(option.maxDepth===-1||level<option.maxDepth)obj.forEach(function(obj,i){result.push(renderObject(obj,pathName||pathName===""?option.K?i.toString():pathName+(option.R?"/"+i:"["+i+"]"):null,option,level))})}else if(obj.constructor===Object){if((option.J||option.R)&&!option.P&&(pathName||pathName===""))result.push(indent+pathName+(option.C?": Object":""));else if((pathName||pathName==="")&&!option.P)result.push(indent+pathName+(option.K?!option.C?"":typeString:level===option.maxDepth?"="+JSON.stringify(obj,null,0):"={}"));if(option.maxDepth===-1||level<option.maxDepth)for(var key in obj)if(obj.hasOwnProperty(key)){if(pathName||pathName===""){var keyEsc=option.R?key.replace(/~/g,"~0").replace(/\//g,"~1"):key.replace(/\n/g,"\\n").replace(/[\b]/g,"\\b").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001f\u007f]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).substr(-4)});if(option.d&&!option.R&&/^[A-Za-z_$][$\w\d]*$/.test(key))var thisPath=(option.K?"":pathName+".")+keyEsc;else if(option.K)var thisPath=keyEsc;else var thisPath=option.R?pathName+"/"+key.replace(/~/g,"~0").replace(/\//g,"~1"):pathName+"["+keyQuotes+(option.q?keyEsc.replace(/'/g,"\\'"):keyEsc.replace(/"/g,'\\"'))+keyQuotes+"]"}result.push(renderObject(obj[key],thisPath,option,level))}}else if(option.T){if(typeof obj==="string"){if(option.e)obj=obj.replace(/\n/g,"\\n").replace(/[\b]/g,"\\b").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t");if(option.encoding.x||option.encoding["0"]||option.encoding.h||option.encoding.H||option.encoding.O||option.encoding.o||option.encoding.b||option.encoding["%"]&&option.A){var tempArray=[];if(option.encoding.x)var escStr="\\x",stringBase=16;else if(option.encoding.h||option.encoding.H)var escStr="",stringBase=16,spc=" ";else if(option.encoding["%"])var escStr="%",stringBase=16;else if(option.encoding["0"])var escStr="\\0",stringBase=8;else if(option.encoding.O)var escStr="\\",stringBase=8,spc="";else if(option.encoding.o)var escStr="0o",stringBase=8,spc=" ";else if(option.encoding.b)var escStr="",stringBase=2,stringPadding="00",spc=" ";for(var i=0;i<obj.length;i++){var charcode=obj.charCodeAt(i);if(charcode<128)if(option.encoding.b)tempArray.push(("0000000"+charcode.toString(2)).slice(-8)," ");else if(option.encoding.o)tempArray.push(escStr,charcode.toString(stringBase),spc);else if((option.encoding.O||option.encoding["0"])&&option.A)tempArray.push(escStr,("00"+charcode.toString(stringBase)).slice(-3),spc);else if((option.encoding.h||option.encoding.H||option.encoding.x)&&option.A)tempArray.push(escStr,("0"+charcode.toString(stringBase)).slice(-2),spc);else tempArray.push(obj.charAt(i));else if(charcode<2048)tempArray.push(escStr,(192|charcode>>6).toString(stringBase),spc,escStr,(128|charcode&63).toString(stringBase),spc);else if(charcode<55296||charcode>=57344)tempArray.push(escStr,(224|charcode>>12).toString(stringBase),spc,escStr,(128|charcode>>6&63).toString(stringBase),spc,escStr,(128|charcode&63).toString(stringBase),spc);else{i++;charcode=65536+((charcode&1023)<<10|obj.charCodeAt(i)&1023);tempArray.push(escStr,(240|charcode>>18).toString(stringBase),spc,escStr,(128|charcode>>12&63).toString(stringBase),spc,escStr,(128|charcode>>6&63).toString(stringBase),spc,escStr,(128|charcode&63).toString(stringBase),spc)}}obj=tempArray.join("");if(option.encoding.H)obj=obj.toUpperCase()}else if(option.encoding["%"]&&!option.A)obj=encodeURI(obj);else if(option.encoding.B||option.encoding["6"])obj=obj.replace(/[\u0000-\uFFFF]/g,function(chr){var b=("000000000000000"+chr.charCodeAt(0).toString(2)).slice(-16);return(option.encoding.B?b.substring(0,8)+" "+b.substring(8,16):b)+" "});else if(option.encoding.u){if(option.A)var rangeRegex=/[\u0000-\uFFFF]/g;else var rangeRegex=/[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f-\uFFFF]/g;obj=obj.replace(rangeRegex,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)})}else if(option.encoding.U||option.encoding.E){var tempArray=[];if(option.encoding.U)var escStr="\\U",padding="000000",paddingOffset=-8;else if(option.encoding.E)var escStr="\\u",padding="",paddingOffset=0,open="{",close="}";for(var i=0;i<obj.length;i++){var charcode=obj.charCodeAt(i);if(charcode<32)tempArray.push(escStr,open,(padding+charcode.toString(16)).slice(paddingOffset),close);else if(charcode<128&&!option.A)tempArray.push(obj.charAt(i));else if(charcode<55296||charcode>=57344)tempArray.push(escStr,open,(padding+charcode.toString(16)).slice(paddingOffset),close);else{i++;tempArray.push(escStr,open,(padding+((charcode-55296)*1024+obj.charCodeAt(i)-56320+65536).toString(16)).slice(paddingOffset),close)}}obj=tempArray.join("")}}else if(obj.constructor===Number)if(option.encoding.b||option.encoding.B||option.encoding["6"]){obj=obj.toString(2);if(option.encoding.b&&obj.length<8)obj=("0000000"+obj).slice(-8);else if((option.encoding["6"]||option.encoding.B)&&obj.length<16)obj=("000000000000000"+obj).slice(-16)}else if(option.encoding.h||option.encoding.H)obj=("0"+(option.encoding.h?obj.toString(16):obj.toString(16).toUpperCase())).slice(-2);else if(option.encoding.O)obj="0"+obj.toString(8);else{if(option.encoding.o)obj="0o"+obj.toString(8)}else if(obj.constructor===Boolean&&(option.encoding.b||option.encoding.B||option.encoding["6"]))obj=obj?"1":"0";result=[indent+obj]}else if(option.R||option.J)result=[indent+pathName+(!option.C?"":typeString)];else if(typeof obj==="string"&&!isNull){var thisString=obj.replace(/\n/g,"\\n").replace(/[\b]/g,"\\b").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u001f\u007f]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)});var thisString=stringQuotes==="'"?thisString.replace(/'/g,"\\'"):thisString.replace(/"/g,'\\"');result=[pathName+"="+stringQuotes+thisString+stringQuotes]}else result=[pathName+"="+obj];return result.flat()}function objectifyExpressions(array,option){option=option||{};try{array=array.map(function(expr){var pathStack=[];var baldRecursion=false;expr=expr.replace(/^\s*/,"").replace(/\s*$/,"");if(expr===""||expr[0]==="/"){var assignmentLocations=[];option.allowExpressions=false;pathStack=expr.split("/");pathStack.shift();pathStack=pathStack.map(function(f){return f.replace(/~1/g,"/").replace(/~0/g,"~")});if(pathStack[pathStack.length-1]==="-")pathStack[pathStack.length-1]={"expression":"-"}}else if(expr[0]==="$"){var revExpr=expr.split("").reverse().join("");var tempExpr=revExpr.replace(/(["'])(.*?)\1(?!\\)|(\/.*?\/(?!\\)\s*~=)|=~*\s(\/.*?\/(?!\\))|(={2,3})[^=]|[^=](==?!)|[^=]((?:=!|=<|=>|~=))/g,function(a){return a.replace(/./g," ")});var assignmentRegex=/=/g;var assignmentLocations=[];var lastAssignmentLastIndex=0;var assignmentMatch=[];do{assignmentMatch=assignmentRegex.exec(tempExpr);if(assignmentMatch===null||assignmentRegex.lastIndex===0||lastAssignmentLastIndex===assignmentRegex.lastIndex)break;lastAssignmentLastIndex=assignmentRegex.lastIndex;assignmentLocations.unshift(lastAssignmentLastIndex)}while(assignmentRegex.lastIndex!==0&&assignmentRegex.lastIndex!==tempExpr.length);if(option.disallowData&&assignmentLocations.length)throw new SyntaxError("Data assignment (=) not allowed in path specification");else if(assignmentLocations.length>1)throw new SyntaxError("Multiple assignment operators detected: "+expr);if(expr.length-lastAssignmentLastIndex>0)var revExpr=expr.substring(0,expr.length-lastAssignmentLastIndex).split("").reverse().join("");else throw new Error("Error parsing: "+expr);var hasRoot,lastLastIndex=0;var Level1Regex=/([\w\d$]*[A-Za-z_$])(\.{1,2})|(\*?)(\.{1,2})|(\])|(\$)/g;do{var L1Match=Level1Regex.exec(revExpr);if(L1Match===null)break;if(lastLastIndex+L1Match[0].length!==Level1Regex.lastIndex||L1Match[0]==="")throw new SyntaxError("Malformed path expression: "+expr);if(L1Match[1]||L1Match[3]){if(baldRecursion)throw new SyntaxError("Additional operators (./..) disallowed after recursive descent: "+expr);L1Match=L1Match.filter(function(p){return p!=null});if(L1Match[1]==="*"){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+exprPath.split("").reverse().join(""));pathStack.unshift({"expression":"*"})}else if(L1Match[1])pathStack.unshift(L1Match[1].split("").reverse().join(""));if(L1Match[2]===".."){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+exprPath.split("").reverse().join(""));pathStack.unshift({"expression":".."})}else if(L1Match[1]===""){Level1Regex.lastIndex=lastLastIndex;break}}else if(L1Match[4]){if(L1Match[4]===".")break;else if(!pathStack.length){baldRecursion=true;break}else if(pathStack[0].expression==="..")throw new SyntaxError("Additional operators (./..) disallowed after recursive descent: "+expr);pathStack.unshift({"expression":".."})}else if(L1Match[5]){baldRecursion=false;var Level2Regex=/\s*(["'])(.*?)\1(?!\\)|(\*(?!:\*))|(\d+\-?)|(-)|(,)|(:)|(\))|(\[)|\s/g;var subArray=[],L2Match=[],subLastLastIndex=Level1Regex.lastIndex,pendingData=[],intraSlice=false,needsDelimiter=false,isSlice=false;var openBracket=0,closedBracket=1;Level2Regex.lastIndex=Level1Regex.lastIndex;do{L2Match=Level2Regex.exec(revExpr);if(L2Match===null||subLastLastIndex===Level2Regex.lastIndex||subLastLastIndex+L2Match[0].length!==Level2Regex.lastIndex)throw new SyntaxError("Malformed path expression : "+expr);L2Match=L2Match.map(function(s){return!s?s:s.split("").reverse().join("")});if(L2Match[2]==="")subArray.unshift(L2Match[2]);else if(L2Match[2]){if(needsDelimiter){Level2Regex.lastIndex=subLastLastIndex;break}else needsDelimiter=true;if(intraSlice)break;pendingData.unshift(L2Match[2].replace(/\\'/g,"'").replace(/\\"/g,'"').replace(/\\n/g,"\n").replace(/\\b/g,"\b").replace(/\\f/g,"\f").replace(/\\r/g,"\r").replace(/\\t/g,"\t").replace(/\\u([0-9a-fA-F]{4})/g,function($0,$1){return String.fromCharCode(parseInt($1,16))}))}else if(L2Match[3]){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+exprPath.split("").reverse().join(""));if(needsDelimiter){Level2Regex.lastIndex=subLastLastIndex;break}else needsDelimiter=true;if(intraSlice)break;else pendingData.unshift({"expression":"*"})}else if(L2Match[4]){if(needsDelimiter&&!isSlice){Level2Regex.lastIndex=subLastLastIndex;break}else needsDelimiter=true;if(isSlice&&intraSlice)intraSlice=false;if(L2Match[4]!=="0"&&(L2Match[4][0]==="0"||L2Match[4][0]==="-"&&L2Match[4][1]==="0"))throw new Error("Octal indices are disallowed: "+L2Match[4]);else pendingData.unshift(Number(L2Match[4]))}else if(L2Match[5]){if(needsDelimiter){Level2Regex.lastIndex=subLastLastIndex;break}else needsDelimiter=true;pendingData.unshift({"expression":"-"})}else if(L2Match[6]){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+exprPath.split("").reverse().join(""));if(pendingData.length&&!isSlice)subArray.unshift(pendingData[0]);else if(pendingData.length){if(isSlice&&intraSlice)pendingData.unshift(null);subArray.unshift({"expression":pendingData})}pendingData=[],needsDelimiter=false;if(isSlice){intraSlice=false;isSlice=false}}else if(L2Match[7]){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+exprPath.split("").reverse().join(""));isSlice=true;if(pendingData.length===1&&pendingData[0]!==null&&(pendingData[0].constructor===String||!(pendingData[0].constructor===Number||pendingData[0].expression[0]==="(")))break;if(!pendingData.length||intraSlice)pendingData.unshift(null);if(!intraSlice)intraSlice=true}else if(L2Match[8]){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+exprPath.split("").reverse().join(""));var openParens=0,closeParens=1,L3Match=[];var filterText=L2Match[8];var Level3Regex=/(["'])(.*?)\1(?!\\)|(\()|(\))|(\/.*?\/(?!\\)\s*~=)|(~=\s*\/.*?\/(?!\\))|(==?((?:=|!)))|(.)/g;if(isSlice)intraSlice=false;else if(needsDelimiter)break;Level3Regex.lastIndex=Level2Regex.lastIndex;do{L3Match=Level3Regex.exec(revExpr);if(L3Match[1])filterText+=L3Match[0].replace(/@/g,"@\\");else if(L3Match[3]){filterText+=L3Match[3];openParens+=1}else if(L3Match[4]){filterText+=L3Match[4];closeParens+=1}else if(L3Match[5]||L3Match[6])filterText+=L3Match[0].replace(/@/g,"@\\");else if(L3Match[7])filterText+="=="+L3Match[8];else if(L3Match[9]){if(L3Match[9]==="="&&!/[<>!]/.test(revExpr[Level3Regex.lastIndex]))break;filterText+=L3Match[9]}if(closeParens===openParens){needsDelimiter=true;if(revExpr[Level3Regex.lastIndex]==="?"){if(isSlice){Level3Regex.lastIndex=0;break}filterText+="?";Level3Regex.lastIndex=Level3Regex.lastIndex+1}Level2Regex.lastIndex=Level3Regex.lastIndex;var filterTextFinal=filterText.split("").reverse().join("");pendingData.unshift({"expression":filterTextFinal});break}}while(Level3Regex.lastIndex!==0&&Level3Regex.lastIndex!==revExpr.length);if(closeParens!==openParens)break}else if(L2Match[9])if(Level2Regex.lastIndex-Level1Regex.lastIndex===1)break;else{Level1Regex.lastIndex=Level2Regex.lastIndex;break}subLastLastIndex=Level2Regex.lastIndex}while(Level2Regex.lastIndex!==0&&Level2Regex.lastIndex!==revExpr.length);if(pendingData.length===1&&!isSlice)subArray.unshift(pendingData[0]);else if(pendingData.length){if(isSlice&&intraSlice)pendingData.unshift(null);if(pendingData[2]===undefined)pendingData[2]=null;subArray.unshift({"expression":pendingData})}if(subArray.length>1){if(!option.allowExpressions)throw new SyntaxError("JSONPath expressions disallowed: "+exprPath.split("").reverse().join(""));pathStack.unshift(subArray)}else pathStack.unshift(subArray[0])}else if(L1Match[6])if(Level1Regex.lastIndex===revExpr.length)hasRoot=true;else break;lastLastIndex=Level1Regex.lastIndex}while(Level1Regex.lastIndex!==0&&Level1Regex.lastIndex!==revExpr.length);if(!hasRoot||baldRecursion||Level1Regex.lastIndex!==revExpr.length&&!lastAssignmentLastIndex)throw new SyntaxError("Malformed path expression: "+expr);}else throw new SyntaxError("Unrecognized query syntax: "+expr);if(assignmentLocations.length===1){if(expr.charAt(expr.length-lastAssignmentLastIndex-1)==="=")return"";var assignmentData=expr.substring(expr.length-lastAssignmentLastIndex+1,expr.length);if(assignmentData.match(/^'(.*)'$/))assignmentData='"'+assignmentData.substring(1,assignmentData.length-1).replace(/\\"/g,'"').replace(/\\'/g,"'").replace(/"/g,'\\"')+'"';try{var assignmentData_obj=JSON.parse(assignmentData,null,0)}catch(e){throw new SyntaxError(e+": "+assignmentData);}}if(pathStack.length&&pathStack[pathStack.length-1].constructor===Array&&option.expandTrailingUnion){var returnObject=[];var basePath=pathStack.slice();var childUnion=basePath.pop();for(var i=0;i<childUnion.length;i++){var thisChild=childUnion[i];var tempBasePath=basePath.slice();tempBasePath.push(thisChild);returnObject.push({"path":tempBasePath,"data":assignmentData_obj})}return returnObject}else{var returnObject={"path":pathStack,"data":assignmentData_obj};return returnObject}})}catch(e){throw new Error(e);}return array.filter(function(e){return e}).flat()}function sortObject(obj){if(Array.isArray(obj))var seed=[];else if(typeof obj==="object"&&obj!==null)var seed={};else return obj;return Object.keys(obj).sort().reduce(function(result,key){if(typeof obj[key]==="object")result[key]=sortObject(obj[key]);else result[key]=obj[key];return result},seed)}function flatten(){var flat=[];for(var i=0;i<arguments.length;i++)if(arguments[i]instanceof Array)flat.push.apply(flat,flatten.apply(this,arguments[i]));else flat.push(arguments[i]);return flat}if(!Array.prototype.flat)Object.defineProperty(Array.prototype,"flat",{configurable:true,value:function flat(){var depth=isNaN(arguments[0])?1:Number(arguments[0]);return depth?Array.prototype.reduce.call(this,function(acc,cur){if(Array.isArray(cur))acc.push.apply(acc,flat.call(cur,depth-1));else acc.push(cur);return acc},[]):Array.prototype.slice.call(this)},writable:true});Object.defineProperty(Array.prototype,"sortVarWidth",{configurable:true,value:function sortVarWidth(){var that=this;var sortedUniqLengths=Array.prototype.map.call(this,function(e){return e.length}).filter(function(v,i,arr){return i==arr.indexOf(v)}).sort(function(a,b){return a-b});var sortedArray=[];Array.prototype.forEach.call(sortedUniqLengths,function(l){var chunk=Array.prototype.filter.call(that,function(e){return e.length==l});sortedArray.push(chunk.sort())});return sortedArray.flat()},writable:true});RegExp.quote=function(str){return str.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")};if(!Math.sign)Math.sign=function(x){return(x>0)-(x<0)||+x};(function(root,factory){if(typeof exports==="object")factory(module.exports);else if(typeof define==="function"&&define.amd)define(["exports"],factory);else{root.jsonpatch={};root.returnExports=factory(root.jsonpatch)}})(this,function(exports){var apply_patch,JSONPatch,JSONPointer,_operationRequired,isArray;isArray=Array.isArray||function(obj){return Object.prototype.toString.call(obj)=="[object Array]"};exports.apply_patch=apply_patch=function(doc,patch){return(new JSONPatch(patch)).apply(doc)};function InvalidPatch(message){Error.call(this,message);this.message=message}exports.InvalidPatch=InvalidPatch;InvalidPatch.prototype=new Error;function PatchApplyError(message){Error.call(this,message);this.message=message}exports.PatchApplyError=PatchApplyError;PatchApplyError.prototype=new Error;exports.JSONPointer=JSONPointer=function JSONPointer(pathStr){var i,split,path=[];split=pathStr.split("/");if(""!==split[0])throw new InvalidPatch("JSONPointer must start with a slash (or be an empty string)!");for(i=1;i<split.length;i++)path[i-1]=split[i].replace(/~1/g,"/").replace(/~0/g,"~");this.path=path;this.length=path.length};JSONPointer.prototype._get_segment=function(index,node){var segment=this.path[index];if(isArray(node))if("-"===segment)segment=node.length;else{if(!segment.match(/^0$|^[1-9][0-9]*$/))throw new RangeError("Invalid array index: "+segment);segment=parseInt(segment,10)}return segment};function clone(o){var cloned,key;if(isArray(o))return o.slice();if(o===null)return o;else if(typeof o==="object"){cloned={};for(key in o)if(Object.hasOwnProperty.call(o,key))cloned[key]=o[key];return cloned}else return o}JSONPointer.prototype._action=function(doc,handler,mutate){var that=this;function follow_pointer(node,index){var segment,subnode;if(!mutate)node=clone(node);segment=that._get_segment(index,node);if(index==that.path.length-1)node=handler(node,segment);else{if(isArray(node)){if(node.length<=segment)throw new PatchApplyError("Path not found in document");}else if(typeof node==="object"){if(!Object.hasOwnProperty.call(node,segment))throw new PatchApplyError("Path not found in document");}else throw new PatchApplyError("Path not found in document");subnode=follow_pointer(node[segment],index+1);if(!mutate)node[segment]=subnode}return node}return follow_pointer(doc,0)};JSONPointer.prototype.add=function(doc,value,mutate){if(0===this.length)return value;return this._action(doc,function(node,lastSegment){if(node===null)throw new Error("Unable to add to null!");else if(isArray(node)){if(lastSegment>node.length)throw new RangeError("Array index '"+lastSegment+"' does not exist. Use '-' to add to the end.");node.splice(lastSegment,0,value)}else node[lastSegment]=value;return node},mutate)};JSONPointer.prototype.remove=function(doc,mutate){if(0===this.length)return[];return this._action(doc,function(node,lastSegment){if(!Object.hasOwnProperty.call(node,lastSegment))throw new PatchApplyError("Remove operation must point to an existing value!");if(isArray(node))node.splice(lastSegment,1);else delete node[lastSegment];return node},mutate)};JSONPointer.prototype.replace=function(doc,value,mutate){if(0===this.length)return value;return this._action(doc,function(node,lastSegment){if(node===null)throw new Error("Unable to replace to null!");else if(!Object.hasOwnProperty.call(node,lastSegment))throw new RangeError("Replace requires an existing location. Property '"+lastSegment+"' not found.");if(isArray(node))node.splice(lastSegment,1,value);else node[lastSegment]=value;return node},mutate)};JSONPointer.prototype.get=function(doc){var value;if(0===this.length)return doc;this._action(doc,function(node,lastSegment){if(!Object.hasOwnProperty.call(node,lastSegment))throw new PatchApplyError("Path not found in document");value=node[lastSegment];return node},true);return value};JSONPointer.prototype.subsetOf=function(otherPointer){if(this.length<=otherPointer.length)return false;for(var i=0;i<otherPointer.length;i++)if(otherPointer.path[i]!==this.path[i])return false;return true};_operationRequired={add:["value"],replace:["value"],test:["value"],remove:[],move:["from"],copy:["from"]};function deepEqual(a,b){var key;if(a===b)return true;else if(typeof a!==typeof b)return false;else if("object"===typeof a){var aIsArray=isArray(a),bIsArray=isArray(b);if(aIsArray!==bIsArray)return false;else if(aIsArray)if(a.length!=b.length)return false;else for(var i=0;i<a.length;i++)return deepEqual(a[i],b[i]);else{for(key in a)if(Object.hasOwnProperty(a,key))if(!(Object.hasOwnProperty(b,key)&&deepEqual(a[key],b[key])))return false;for(key in b)if(Object.hasOwnProperty(b,key)&&!Object.hasOwnProperty(a,key))return false;return true}}else return false}function validateOp(operation){var i,required;if(!operation.op)throw new InvalidPatch("Operation missing!");if(!_operationRequired.hasOwnProperty(operation.op))throw new InvalidPatch("Invalid operation!");if(!("path"in operation))throw new InvalidPatch("Path missing!");required=_operationRequired[operation.op];for(i=0;i<required.length;i++)if(operation[required[i]]===undefined)throw new InvalidPatch(operation.op+" must have key "+required[i]);}function compileOperation(operation,mutate){validateOp(operation);var op=operation.op;var path=new JSONPointer(operation.path);var value=operation.value;var from=operation.from!==undefined?new JSONPointer(operation.from):null;switch(op){case "add":return function(doc){return path.add(doc,value,mutate)};case "remove":return function(doc){return path.remove(doc,mutate)};case "replace":return function(doc){return path.replace(doc,value,mutate)};case "move":if(path.subsetOf(from))throw new InvalidPatch("destination must not be a child of source");return function(doc){var value=from.get(doc);var intermediate=from.remove(doc,mutate);return path.add(intermediate,value,mutate)};case "copy":return function(doc){var value=from.get(doc);return path.add(doc,value,mutate)};case "test":return function(doc){if(!deepEqual(path.get(doc),value))throw new PatchApplyError("Test failed. "+path.path+" did not match: "+value);return doc}}}exports.JSONPatch=JSONPatch=function JSONPatch(patch,mutate){this._compile(patch,mutate)};JSONPatch.prototype._compile=function(patch,mutate){var i,_this=this;this.compiledOps=[];if("string"===typeof patch)patch=JSON.parse(patch);if(!isArray(patch))throw new InvalidPatch("Patch must be an array of operations");for(i=0;i<patch.length;i++){var compiled=compileOperation(patch[i],mutate);_this.compiledOps.push(compiled)}};exports.JSONPatch.prototype.apply=function(doc){var i;for(i=0;i<this.compiledOps.length;i++)doc=this.compiledOps[i](doc);return doc}});function isObject(a){var type=typeof a;return a!=null&&(type==="object"||type=="function")}function diff(oldValue,newValue){if(oldValue==newValue)return undefined;if(!(oldValue!=null&&newValue!=null&&typeof newValue==="object"&&typeof oldValue==="object"))return newValue!=null?newValue:null;if(!Array.isArray(oldValue)&&Array.isArray(newValue))return newValue;if(Array.isArray(oldValue)&&!Array.isArray(newValue)){var newValue=JSON.parse(JSON.stringify(newValue));newValue.length=null;return newValue}var patch=undefined;for(var name in oldValue)if(oldValue.hasOwnProperty(name))if(!newValue.hasOwnProperty(name)){if(patch==null)patch={};patch[name]=null}else{var propertyDiff=diff(oldValue[name],newValue[name]);if(propertyDiff!==undefined){if(patch==null)patch={};patch[name]=propertyDiff}}for(var name in newValue)if(newValue.hasOwnProperty(name)&&!oldValue.hasOwnProperty(name)){if(patch==null)patch={};patch[name]=newValue[name]}if(Array.isArray(oldValue)&&Array.isArray(newValue)&&newValue.length<oldValue.length){patch.length=newValue.length;for(var i=newValue.length;i<oldValue.length;i++)delete patch[i]}return patch}function merge(target,patch,deleteNull){if(Array.isArray(target)&&patch!=null&&patch.length===null){target={};delete patch.length}if(patch==null||patch!=null&&patch.constructor!==Object)if(Array.isArray(patch))return JSON.parse(JSON.stringify(patch));else return patch;if(!isObject(target))target={};var deletedValues=false;for(var key in patch){var value=patch[key];if(deleteNull&&value==null){deletedValues=true;delete target[key]}else target[key]=merge(target[key],value,deleteNull)}if(deletedValues&&Array.isArray(target))for(var i=target.length;i>0;i--)if(target[i-1]==null)target.length=i-1;return target}function ingestLiterals(valueString,option,$){function comparePathLengths(a,b){if(a.path.length<b.path.length)return-1;else if(a.path.length>b.path.length)return 1;else return 0}function comparePathContents(a,b){if(a.path<b.path)return-1;else if(a.path>b.path)return 1;else return 0}var literalStrings=valueString.split("\n");try{var literalObjects=objectifyExpressions(literalStrings)}catch(e){throw new Error(e);}literalObjects=literalObjects.sort(comparePathContents).sort(comparePathLengths);if(!option.G)literalObjects=literalObjects.reverse();for(var i=0;i<literalObjects.length;i++){var thisLitObj=literalObjects[i];var thisPath=thisLitObj.path;var thisNode=$;if(thisPath.length>0)for(var j=0;j<thisPath.length;j++){if($===undefined&&!option.I){if(thisPath[j].constructor===String)$={};else if(thisPath[j].constructor===Number)$=[];thisNode=$}var thisKeyName=thisPath[j];if(option.G&&thisLitObj.data===undefined)throw new Error("Gripe Mode: No data for path ending in: "+thisKeyName);if(thisNode===undefined&&option.I)throw new Error("Object literals lack proper initialization, -I is inhibiting inferred path generation");else if(!thisNode.hasOwnProperty(thisKeyName))if(j===thisPath.length-1)if(thisNode.constructor===Array||thisNode.constructor===Object)if(thisLitObj.data!==undefined){if(thisNode.constructor===Array&&thisKeyName.constructor===String)throw new Error("Unable to create key name '"+thisKeyName+"' in the array: "+JSON.stringify(thisNode,null,0));else if(thisNode.constructor===Object&&thisKeyName.constructor===Number&&option.G)throw new Error("Unable to array index '"+thisKeyName+"' in the object: "+JSON.stringify(thisNode,null,0));thisNode[thisKeyName]=thisLitObj.data}else{if(option.g)thisNode[thisKeyName]=null}else if(option.g)continue;else throw new Error("Key name '"+thisKeyName+"' does not exist and cannot be assigned value: "+thisLitObj.data);else if(!option.I&&j!==thisPath.length-1){if(thisPath[j+1].constructor===String){if(option.G&&thisNode.constructor===Array&&thisKeyName.constructor===String)throw new Error("Gripe Mode: Unable to create inferred object with key name '"+thisKeyName+"' in an array!");else if(option.G&&thisNode.constructor===Object&&thisKeyName.constructor===Number)throw new Error("Gripe Mode: Unable to create inferred array index "+thisKeyName+" in an object!");thisNode[thisKeyName]={}}else if(thisPath[j+1].constructor===Number){if(option.G&&thisNode.constructor===Array&&thisKeyName.constructor===String)throw new Error("Gripe Mode: Unable to create inferred object with key name '"+thisKeyName+"' in an array!!");else if(option.G&&thisNode.constructor===Object&&thisKeyName.constructor===Number)throw new Error("Gripe Mode: Unable to create inferred array index "+thisKeyName+" in an object!!");thisNode[thisKeyName]=[]}thisNode=thisNode[thisKeyName]}else{if(j!==thisPath.length-1)throw new Error("Node does not exist: "+thisKeyName);}else if(j!==thisPath.length-1)thisNode=thisNode[thisKeyName];else if(thisLitObj.data!==undefined){var thisLitObjDataString=JSON.stringify(thisLitObj.data,null,0);if(option.G&&(thisLitObjDataString==="{}"||thisLitObjDataString=="[]"))thisNode[thisKeyName]=thisLitObj.data;else;}else;}else if(thisPath.length>0&&$===undefined)throw new Error("Unable to assign value to path /"+thisPath.map(function(p){return p.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")+" because the object is undefined");else if(!thisPath.length&&$===undefined&&thisLitObj.data)$=thisLitObj.data}return $!==undefined?JSON.parse(JSON.stringify($)):[]}function alterObject(obj,valueArg,fromArg,pathArg,option){if(!(option.x||option.X)){var opArg,pathArgValidated=[],fromArgValidated;if(Object.keys(option.opArg)[0]!==undefined)opArg=Object.keys(option.opArg)[0];if(valueArg!==undefined){if(option.V)try{valueArg=readFile(valueArg)}catch(error){throw new Error(error);}if(option.s)valueArg='"'+valueArg.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/[\b]/g,"\\b").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f-\uFFFF]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)})+'"';try{valueArg=JSON.parse(valueArg)}catch(e){throw new Error(e);}}if(fromArg!==undefined)if(fromArg==="$")fromArgValidated="";else if(fromArg[0]==="$"){try{fromArgValidated=jsonPath(obj,fromArg,{resultType:"PATH_JSONPOINTER"})}catch(error$0){throw new Error(error$0);}if(!fromArgValidated.length)throw new Error("Unable to resolve from path: "+fromArg);else if(fromArgValidated.length>1)throw new RangeError('Error: "From" path returned multiple results: '+fromArg+"\n"+fromArgValidated.join("\n"));else fromArgValidated=fromArgValidated[0]}else fromArgValidated=fromArg;if(pathArg!==undefined)if(pathArg==="$")pathArgValidated=[""];else if(pathArg[0]==="$"){try{pathArgValidated=objectifyExpressions([pathArg],{"expandTrailingUnion":true,"allowExpressions":true})}catch(error$1){throw new Error(error$1);}pathArgValidated=pathArgValidated.map(function(p){try{var xp=jsonPath(obj,p.path,{resultType:"PATH_JSONPOINTER"})}catch(error$2){throw new Error(error$2);}if(xp.length)return xp;else if(!xp.length&&option.G&&(option.opArg.remove||option.opArg.replace||option.opArg.test))return"/"+p.path.map(function(p){return p.toString().replace(/~/g,"~0").replace(/\//g,"~1")}).join("/");else if(!xp.length&&(option.opArg.remove||option.opArg.replace||option.opArg.test))return"";var pp=p.path.slice();var pc=pp.pop();if(!pp.length&&pc.expression==="-")var possiblePaths="/-";else if(pp.length){var ppv=jsonPath(obj,pp,{resultType:"PATH_OBJECT"});if(!ppv.length)return"";var possiblePaths=ppv.map(function(ppve){ppve.path.push(pc.expression==="-"?"-":pc);if(pc!==null&&(pc.constructor===String||pc.constructor===Array||pc.expression==="-")){var ppve_jp="/"+ppve.path.map(function(p){return p.toString().replace(/~/g,"~0").replace(/\//g,"~1")}).join("/");return ppve_jp}else return""})}else if(obj!==null&&(pc.constructor===Number&&Array.isArray(obj)||pc.constructor===String&&obj.constructor===Object))var possiblePaths="/"+p.path.map(function(p){return p.toString().replace(/~/g,"~0").replace(/\//g,"~1")}).join("/");else possiblePaths="";return possiblePaths}).flat().sortVarWidth().reverse().filter(function(p){return p!=null&&p!=""}).filter(function(item,pos,ary){return!pos||item!=ary[pos-1]});if(!pathArgValidated.length&&option.G)throw new Error("Unable to resolve path: "+pathArg);else if(pathArgValidated.length>1)if(option.opArg.move)throw new Error("Move operation cannot have multiple destinations: "+pathArg+"\n"+pathArgValidated.join("\n"));}else if(pathArg===""||pathArg[0]==="/")pathArgValidated=[pathArg];else throw SyntaxError("Unrecognized query syntax: "+pathArg);}if(option.opArg.mergepatch||option.opArg.merge)if(valueArg!==undefined&&fromArgValidated!==undefined)throw new Error("Merge source ambiguous. Specify a value (-v/-V) or a path (-p), or neither.");else if(valueArg===undefined&&fromArgValidated===undefined)throw new SyntaxError("Merge source not given, specify a path (-p) or a JSON value (-v/-V).");else{if(fromArgValidated){try{var rawVal=jsonPath(obj,objectifyExpressions([fromArgValidated])[0].path,null)[0]}catch(e$3){throw new Error(e$3);}valueArg=rawVal;if(valueArg===undefined)throw new Error("From path does not exist: "+fromArgValidated);}else if(fromArgValidated==="")valueArg=jsonPath(obj,[],null)[0];if(!pathArgValidated.length)obj=merge(obj,valueArg,option.opArg.mergepatch?true:false);else pathArgValidated.forEach(function(p){try{var pval=jsonPath(obj,objectifyExpressions([p])[0].path,null)[0]}catch(e$4){throw new Error(e$4);}var mergedValue=merge(pval,valueArg,option.opArg.mergepatch?true:false);try{obj=jsonpatch.apply_patch(obj,[{"op":"replace","path":p,"value":mergedValue}])}catch(e$5){throw new Error(e$5);}})}else if(option.opArg.diff)if(valueArg!==undefined)obj=diff(obj,valueArg,true);else throw new SyntaxError("No value specified!");else{if(option.x)var opArray=JSON.parse(JSONPatchArg);else if(option.X)var opArray=JSON.parse(readFile(JSONPatchArg));else if(pathArgValidated.length){var opArray=[{}];for(i=0;i<pathArgValidated.length;i++)opArray[i]={"op":opArg,"path":pathArgValidated[i],"from":fromArgValidated,"value":valueArg}}else throw new Error("JSON Patch operation with no path provided!");try{obj=jsonpatch.apply_patch(obj,opArray)}catch(e$6){throw new Error(e$6);}}return obj}if(typeof printErr==="undefined")var printErr$7=function(string){debug(string)};var option={};var maxSize={};maxSize.print=715827882-2;maxSize.file=2147483647;var query=decodeURIComponent(escape(arguments[0]))||"$";var fileArg=decodeURIComponent(escape(arguments[1]))||"/dev/stdin";var optionsArg=arguments[2]||"";for(var i=0;i<optionsArg.length;i++)switch(optionsArg.charAt(i)){case "Q":option.Q=true;option.q=true;break;default:option[optionsArg.charAt(i)]=true;break}var spaceArgString=decodeURIComponent(escape(arguments[3]))||"2";var spaceArg=/^\s*$/.test(spaceArgString)||isNaN(spaceArgString)?spaceArgString:Number(spaceArgString);option.spaceArg=spaceArg;if(option.v||option.V)var valueArg=decodeURIComponent(escape(arguments[4]));else var valueArg=undefined;if(option.p)var pathArg=decodeURIComponent(escape(arguments[5]));option.maxDepth=arguments[6]!==""&&!isNaN(Number(arguments[6]))?Number(arguments[6]):-1;if(arguments[7][0]){option.encoding={};option.encoding[decodeURIComponent(escape(arguments[7][0]))]=true}else option.encoding="";option.opArg={};if(option.o)option.opArg[decodeURIComponent(escape(arguments[8])).toLowerCase()]=true;if(option.f)var fromArg=decodeURIComponent(escape(arguments[9]));var JSONPatchArg=decodeURIComponent(escape(arguments[10]))||"";if(typeof readFile==="function")try{var fileText=readFile(fileArg)}catch(error){quit()}else{if(option.V){printErr('-V not available for this version of jsc\nUse -v "$(< file)" as a workaround');quit()}var fileText="";while(line=decodeURIComponent(escape(this.readline())))fileText+=line+"\n"}if(!(option.S||option.s)&&/^\s*\$/.test(fileText)){if(option.k){printErr("Literals processing forbidden! Exiting.");quit()}try{var obj=ingestLiterals(fileText,option)}catch(e){printErr(e);quit()}}else{if(option.S){var tempJSON='"'+fileText.slice(0,-1).replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/[\b]/g,"\\b").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f-\uFFFF]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)})+'"';fileText=tempJSON}else fileText=fileText.replace(/\n/gm,"");try{var obj=JSON.parse(fileText)}catch(error$8){printErr("JSON Input Data: "+error$8);quit()}}if(option.opArg.constructor===Object&&Object.keys(option.opArg).length)try{var obj=alterObject(obj,valueArg,fromArg,pathArg,option)}catch(e$9){printErr(e$9);quit()}if((query==="$"||query==="")&&!option.j&&!option.r)var resultObject=obj;else{try{var queryObject=objectifyExpressions([query],{"disallowData":true,"allowExpressions":true})[0].path}catch(e$10){printErr(e$10);quit()}try{var resultObject=jsonPath(obj,queryObject,option.j||option.r?{"resultType":option.d?"PATH_DOTTED":option.r?"PATH_JSONPOINTER":"PATH","singleQuoteKeys":option.q}:null)}catch(error$11){printErr(error$11);quit()}}if(!option.a&&Array.isArray(resultObject)&&resultObject.length===1)resultObject=resultObject[0];else if(option.a&&!Array.isArray(resultObject))resultObject=[resultObject];if(option.N&&resultObject!==null)while(Array.isArray(resultObject)&&resultObject.length===1){if(option.a&&resultObject[0].constructor===Object)break;if(!resultObject.some(function(val){return val!=null&&typeof val==="object"}))break;resultObject=resultObject[0]}if(option.t&&(resultObject===null||!(Array.isArray(resultObject)||resultObject.constructor===Object)))option.T=true;if(option.l){if(resultObject===null)print("0");else if(Array.isArray(resultObject)||resultObject.constructor===String)print(resultObject.length);else if(resultObject.constructor===Object)print(Object.keys(resultObject).length);else if(resultObject.constructor===Number)print(String(resultObject).replace(/[^0-9]/g,"").length);else print("1");quit()}if(option.O)resultObject=sortObject(resultObject);if(option.F&&Array.isArray(resultObject))resultObject=flatten(resultObject);if(option.T||option.L||option.J||option.R||(option.j||option.r)&&!option.a){if(!option.j&&!option.r)var resultObject=renderObject(resultObject,!option.T?option.R?"":"$":null,option);if(resultObject===null)var resultText=option.n?"null":"";else if(Array.isArray(resultObject))var resultText=resultObject.join("\n");else var resultText=resultObject.toString()}else try{var resultText=JSON.stringify(resultObject,null,spaceArg)}catch(error$12){printErr("JSON.stringify "+error$12)}if(option.u&&!option.T)resultText=resultText.replace(/[\u0000-\u0009\u000b\u000c\u000e-\u001f\u007f-\uFFFF]/g,function(chr){return"\\u"+("0000"+chr.charCodeAt(0).toString(16)).slice(-4)});if(option.encoding["%"]&&(option.r||option.R))resultText=resultText.split("\n").map(function(a){return"#"+encodeURI(a)}).join("\n");if(!(!option.a&&Array.isArray(resultObject)&&resultObject.length===0))if(resultText.length>maxSize.print)jscChunkPrint(resultText);else try{print(resultText)}catch(error$13){printErr("print "+error$13)};
EOF
[ -n "$BASH_VERSION" ] && unset OPTIND OPTARG; local alterOp option options outputOpt depth valueArg; while getopts ":KkDSQPAE:Ff:lNLOuo:i:aCIehdnqgGJzjsRrTtZ:v:V:x:X:p:" option; do case "${option}" in 't'|'r'|'l'|'j'|'T'|'L'|'J'|'R')[ -z "${outputOpt}" ] && outputOpt="${option}" ;;'o')[ -z "${alterOp}" ] && { options+="${option}"; alterOp="${OPTARG}"; } ;;'p')[ -z "${pathArg}" ] && { options+="${option}"; pathArg="${OPTARG}"; } ;;'v'|'V')[ -z "${valueArg}" ] && { options+="${option}"; valueArg="${OPTARG}"; } ;;'f')[ -z "${fromArg}" ] && { options+="${option}"; fromArg="${OPTARG}"; } ;;'x'|'X')[ -z "${JSONPatchArg}" ] && { options+="${option}"; JSONPatchArg="${OPTARG}"; } ;;'i')options+="${option}"; spaceArg="${OPTARG}";;'Z')depthArg="${OPTARG}";;'E')[ -z "${encodingArg}" ] && encodingArg+="${OPTARG}";;'h')echo "${helpText}" > /dev/stderr; exit;;'?'):;;*)options+="${option}";;esac; done; options+="${outputOpt}"; [ $OPTIND -ge 2 ] && shift $((OPTIND-1)); local queryArg="${1}"; local fileArg="${2}";[ -f "${queryArg}" -a -z "${fileArg}" ] && local fileArg="${queryArg}" && unset queryArg;local locations; locations=( "/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Helpers/jsc" "/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc"); local loc; for loc in ${locations[@]}; do [ -x "${loc}" ] && local jsc="${loc}" && break; done;[ -z "${jsc}" ] && jsc=$(which jsc); if [ -z "${jsc}" ]; then locations=( "/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current" "/usr/bin/jsc" "/usr/libexec/webkit2gtk*");for loc in ${locations[@]}; do jsc=$(find -L "${loc}" -name 'jsc' -maxdepth 2 2>/dev/null);[ -n "${jsc}" ] && break;done;fi;[ -z "${jsc}" ] && echo "Unable to locate a jsc binary!" && exit 1;if [ -n "${fileArg}" -a ! -f "${fileArg}" -a "${fileArg}" != '/dev/stdin' ]; then echo "File not found: ${fileArg}" >&2;return 1;elif [ -n "${fileArg}" ]; then readFileSupport="$(${jsc} -e 'print(typeof readFile === "function")')"; fi;if [ "$(stat -f %z "${fileArg:=/dev/stdin}")" -ge 2147483648 ]; then echo "File exceeds maximum size (2GiB)!" >&2; return 1; fi; local errOut; if [ "${readFileSupport}" = "false" ]; then { errOut=$( { { "${jsc}" -e "${JSCode}" -- "${queryArg}" "" "${options}" "${spaceArg}" "${valueArg}" "${pathArg}" "${depthArg}" "${encodingArg}" "${alterOp}" "${fromArg}" "${JSONPatchArg}" <<< "$(sed '/^$/d' "${fileArg:-/dev/stdin}")" ; } 1>&3 ; } 2>&1); } 3>&1; elif [ -f "${fileArg:=/dev/stdin}" ]; then { errOut=$( { { "${jsc}" -e "${JSCode}" -- "${queryArg}" "${fileArg}" "${options}" "${spaceArg}" "${valueArg}" "${pathArg}" "${depthArg}" "${encodingArg}" "${alterOp}" "${fromArg}" "${JSONPatchArg}"; } 1>&3 ; } 2>&1); } 3>&1; else { errOut=$( { { "${jsc}" -e "${JSCode}" -- "${queryArg}" "/dev/stdin" "${options}" "${spaceArg}" "${valueArg}" "${pathArg}" "${depthArg}" "${encodingArg}" "${alterOp}" "${fromArg}" "${JSONPatchArg}" <<< "$(cat)"; } 1>&3 ; } 2>&1); } 3>&1; fi;if [ -n "$(sed -e '/^--> Debug:/d' <<< "${errOut}")" ]; then /bin/echo "$errOut" >&2; return 1; fi
#turn xtrace back on if needed
[ -n "$xtraceFlag" ] && set -x
}
#get a token if we need one (in this case we always do)
function ensureTokenHeader {
local APIUSER="${1}"
local APIPASS="${2}"
local APIURL="${3}"
#error out if either of these are blank
[ -z "${APIUSER}" ] && echo "ERROR: NO USER" >&2 && exit
[ -z "${APIPASS}" ] && echo "ERROR: NO PASSWORD" >&2 && exit
#if we don't need a new token don't get one
local epochNow=$(( $(date +"%s") * 1000 ))
if [ ${epochNow} -lt ${tokenExpiration:-0} -a -n "${tokenBearingHeader}" ]; then
echo "${tokenBearingHeader}"
return
fi
local tokenRequest=$(/usr/bin/curl -s -q "${sslOpt}" "${APIURL}/uapi/auth/tokens" -X POST -H "Authorization: Basic $(echo -n "${APIUSER}:${APIPASS}" | base64)")
[ -z "${tokenRequest}" ] && echo "Error: Unable to get token, check credentials, permissions and curl options (sslOpt)." >&2 && return 1
#only bad requests have the httpStatus property name
local httpStatus=$(jpt /httpStatus <<< "${tokenRequest}")
[ -n "${httpStatus}" ] && echo "Error: $httpStatus" >&2 && return 1
local token=$(jpt -T /token <<< "${tokenRequest}")
#these are GLOBALS so they persist
tokenExpiration=$(jpt -T /expires <<< "${tokenRequest}")
tokenBearingHeader="Authorization: Bearer $token"
echo "${tokenBearingHeader}"
}
function ensureAPIURL {
if [ -z "${APIURL}" ]; then
local enrolledAPIURL=$(defaults read /Library/Preferences/com.jamfsoftware.jamf.plist jss_url 2>/dev/null)
if [ -n "${enrolledAPIURL}" ]; then
echo -n "Enter JSS URL or press reuturn for [${enrolledAPIURL}]: "
read APIURL
[ -z "${APIURL}" ] && APIURL=${enrolledAPIURL}
else
while [ -z "$APIURL" ]; do
echo -n "Enter full JSS URL: "
read APIURL
done
fi
else
echo "APIURL: ${APIURL}"
fi
}
function ensureAPIUSER {
if [ -z "${APIUSER}" ]; then
while [ -z "$APIUSER" ]; do
echo -n "Enter JSS username: "
read APIUSER
done
else
echo "APIUSER: ${APIUSER}"
fi
}
function ensureAPIPASS {
if [ -z "${APIPASS}" ]; then
#turn off echo
stty -echo
while [ -z "$APIPASS" ]; do
echo -n "Enter account password: "
read APIPASS
done
#turn on echo
stty echo
echo
fi
}
########
# MAIN #
########
ensureAPIURL
ensureAPIUSER
ensureAPIPASS
#trim APIURL to just the host name
APIHOSTNAME=$(sed -e 's/^http[s]*:\/\///g' -e 's/:.*$//' -e 's/\/$//' <<< "${APIURL}")
stampedFolder="scripts-${APIHOSTNAME}-${dateStampNow}"
destinationFolder="${myFolderPath}"/"${stampedFolder}"
destinationCSVFilename="scripts-${APIHOSTNAME}-${dateStampNow}.csv"
#get our token for the UAPI call
tokenHeader="$(ensureTokenHeader "${APIUSER}" "${APIPASS}" "${APIURL}")"
[ -z "${tokenHeader}" ] && exit 1
echo "Querying ${APIHOSTNAME}..."
#get our raw JSON reply
rawJSON=$(/usr/bin/curl -s "${sslOpt}" "${APIURL}/uapi/v1/scripts?page=0&page-size=1000" -X GET -H "${tokenHeader}" )
#if httpStatus is present something went wrong
httpResponse=$(jpt /httpStatus <<< "${rawJSON}")
[ -n "${httpResponse}" ] && echo "Error: $httpResponse" && exit
#get the count of scripts
scriptCount=$(jpt -l /results <<< "${rawJSON}")
[ ${scriptCount:-0} -eq 0 ] && echo "No Scripts Found. Exiting." && exit
#make output folder since we do have something
mkdir -p "${destinationFolder}"
#remove the script contents
scriptsStrippedJSON=$(jpt -o remove -p '$..scriptContents' <<< "${rawJSON}")
#get the names of the fields with "-RK" (JSON PointeR Keys only), skip first line (root object), escape any quotes, tr newlines to commas, remove trailing comma
csvHeader=$(jpt -JK $.results[0] <<< "${scriptsStrippedJSON}" | tail -n +2 | sed -e 's/"/""/g' | tr $'\n' , | sed -e 's/,$//')
#start CSV with a header
cat <<< "${csvHeader}" > "${destinationFolder}"/"${destinationCSVFilename}"
echo "Archiving scripts locally..."
#make a scripts subfolder
mkdir -p "${destinationFolder}"/scripts
#output scripts each with a csv
for((i=0; i < ${scriptCount:-0}; i++)); do
#illegal Unix characters : changed to ; and / is changed to \
scriptName=$(jpt -T $.results[$i].name <<< "$rawJSON" | sed -e 's/:/;/g' -e 's/\//\\/' )
#indented bullets for the terminal output
echo -e "\t• ${scriptName}.sh"
#get the text of the script contents
scriptContents=$(jpt -T $.results[$i].scriptContents <<< "$rawJSON" )
#save script with generic .sh for Quicklook if anything, get fancier if you want and analyze the first line
cat <<< "${scriptContents}" > "${destinationFolder}"/scripts/"${scriptName}".sh
#create a csv with header and all script metadata, named the same as the script
cat <<< "${csvHeader}" > "${destinationFolder}"/scripts/"${scriptName}".csv
csvData=$(jpt -Te $.results[$i] <<< "$scriptsStrippedJSON" | sed -e 's/"/""/g' -e 's/\(.*\)/"\1"/g' | tr $'\n' , | sed -e 's/,$//' -e $'s/\\\\n/\\\n/g')
#send script metadata to same named csv
cat <<< "${csvData}" >> "${destinationFolder}"/scripts/"${scriptName}".csv
#send script metadata to combined CSV
cat <<< "${csvData}" >> "${destinationFolder}"/"${destinationCSVFilename}"
#maybe you want to run the script
chmod +x "${destinationFolder}"/scripts/"${scriptName}".sh
done
echo "Done."
[ "$(uname)" == "Darwin" ] && echo "Opening: ${destinationFolder}" && open "${destinationFolder}"