check for the presence of SVGO on launch

(*
	SVGOdrop 1.0.2
	(c) 2016 Superpixel, Nico Rohrbach
*)

property extension_list : {"svg"}

property pretty_code : true
property remove_title : true
property remove_desc : true

on run
	if isSVGOInstalled() is false then
		beep
		display alert "SVGO seem not to be installed!" message
			"Install the tool via \"npm install -g svgo\" and try again." buttons
			{"OK"} default button "OK" as critical
		return
	end if
	set these_items to choose file with multiple selections allowed
	check_files(these_items)
end run

on open these_items
	if isSVGOInstalled() is false then
		beep
		display alert "SVGO seem not to be installed!" message
			"Install the tool via \"npm install -g svgo\" and try again." buttons
			{"OK"} default button "OK" as critical
		return
	end if
	check_files(these_items)
end open

on isSVGOInstalled()
	try
		set temp to do shell script "/bin/bash -l -c 'svgo'"
	on error err_msg number err_num
		if err_num is equal to 127 then
			return false
		else
			return true
		end if
	end try
end isSVGOInstalled

on check_files(these_items)
	repeat with i from 1 to the count of these_items
		set this_item to item i of these_items
		set the item_info to info for this_item
		if folder of the item_info is false then
			try
				set this_extension to the name extension of item_info
			on error
				set this_extension to ""
			end try
			if (this_extension is in the extension_list) then
				process_file(this_item)
			end if
		end if
	end repeat
end check_files

on process_file(this_item)
	set the file_path to the POSIX path of this_item
	-- set options
	set svgo_options to ""
	if pretty_code is true then
		set svgo_options to "--pretty"
	end if
	if remove_title is true then
		set svgo_options to svgo_options & " --enable=removeTitle"
	end if
	if remove_desc is true then
		set svgo_options to svgo_options & " --enable=removeDesc"
	end if
	-- do the job
	try
		do shell script "/bin/bash -l -c 'svgo" & space & svgo_options & space & "\"" & file_path & "\"" & "'"
	on error err_msg number err_num
		beep
		display alert "Error" message err_msg buttons {"OK"} default button "OK" as critical
		return err_num
	end try
end process_file

(*
	SVGOdrop 1.0.1
	(c) 2016 Superpixel, Nico Rohrbach
*)

property extension_list : {"svg"}

property pretty_code : true
property remove_title : true
property remove_desc : true

on run
	set these_items to choose file with multiple selections allowed
	check_files(these_items)
end run

on open these_items
	check_files(these_items)
end open

on check_files(these_items)
	repeat with i from 1 to the count of these_items
		set this_item to item i of these_items
		set the item_info to info for this_item
		if folder of the item_info is false then
			try
				set this_extension to the name extension of item_info
			on error
				set this_extension to ""
			end try
			if (this_extension is in the extension_list) then
				process_file(this_item)
			end if
		end if
	end repeat
end check_files

on process_file(this_item)
	set the file_path to the POSIX path of this_item
	-- set options
	set svgo_options to ""
	if pretty_code is true then
		set svgo_options to "--pretty"
	end if
	if remove_title is true then
		set svgo_options to svgo_options & " --enable=removeTitle"
	end if
	if remove_desc is true then
		set svgo_options to svgo_options & " --enable=removeDesc"
	end if
	-- do the job
	try
		do shell script "/bin/bash -l -c 'svgo" & space & svgo_options & space & "\"" & file_path & "\"" & "'"
	on error err_msg number err_num
		display dialog "Error: " & err_msg buttons {"OK"} with icon stop
		return err_num
	end try
end process_file


Made the iCal script a lot faster

Made the iCal script a lot faster

FasdUAS 1.101.10
k
lQK	An applescript that shows today's events from iCal as growl notifications.
l

a[	The script shows how to register and use multiple types of notifications from Applescript:
l

l		"Today's Events"
l			and
l!		"In-Script Notifications"
lD>			are the two notification types that this script registers.
l@: 			The types of notification are separated functionally.
l|v 			So the user can disable the first informational note from the prefpane without disabling the main notifications.
l!!tn-------------------------------------------------------------------------------------------------------------- "#
"l$$tn--------------------------------------------------------------------------------------------------------------#%&
%l&'(
'l()*
)l*+,
+l--A;	Register with growl and show the "gathering" notification.,./
.l20
0O212
1k13345
4l567
6O89
8k::;<
;r=>
=J??@A
@m	BBToday's EventsAC
Cm
DDIn-Script Notification
>o 0myallnoteslistmyAllNotesList<E
EIF
.registernullnullFGH

appl
GmII-'AppleScript iCal today's Event NotifierHJK

anot
Jo 0myallnoteslistmyAllNotesListKLM

dnot
Lo 0myallnoteslistmyAllNotesListMN

iapp
NmOO
iCal
9mPP2null߀LGrowlHelperApp.appP()P(|0GRRRalisMacintosh HDgH+LGrowlHelperApp.appLȞV	 	ResourcesfȂ6LLLDDYMacintosh HD:Library:PreferencePanes:Growl.prefPane:Contents:Resources:GrowlHelperApp.app&GrowlHelperApp.appMacintosh HDLLibrary/PreferencePanes/Growl.prefPane/Contents/Resources/GrowlHelperApp.app/7QR
QlRS
SI1T
.notifygrnullnullTUV

name
Ul	 !W
Wm !XXIn-Script NotificationVYZ

titl
Yl	"#[
[m"#\\Please WaitZ]^

desc
]l	&)_
_m&)``^XGathering today's events from iCal... (n.b. Events which are repeats will not be shown!)^a

appl
am*-bb-'AppleScript iCal today's Event Notifier
2mP/cd
cldef
el3<g
gr3<hi
hI38
.misccurdldt null
io0nowfjk
jl=Ll
lr=Lmn
m\=Hop
oo=@0now
pl@Gq
qn@Grs
r1CG

time
so@C0now
no0thismorningthisMorningktu
tlMTv
vIMTw
.ascrcmnt********
wlMPx
xoMP0thismorningthisMorninguyz
ylUd{
{rUd|}
|\U`~
~[U^
oUX0thismorningthisMorning
]X]
mXY
1Y\

days
m^_
}o0thiseveningthisEveningz
lel
Iel
.ascrcmnt********
leh
oeh0thiseveningthisEvening
l
l	Gather today's events
lm
Om
ks
lss
rs}
csy
Jsu
mux

list
o0
currentevents
currentEvents
X~U
OP
kO
lZT	Catch events that start today or that started before today, but have not yet ended.
XO
OJ
kI
I
.ascrcmnt********
l
mCURRENT EVENT!
r
1

wr1s
o0thestarttheStart
r
n
1

tstr
o0thestarttheStart
o0thestarttimetheStartTime
r
/
c
+
K
'0
eventtitle
eventTitle
n
1

wr11
o0	thisevent	thisEvent$0eventdescriptioneventDescription
n
1

wr12
o0	thisevent	thisEvent0	starttime	startTime
o #0thestarttimetheStartTime
m'*

reco
o0myrecordmyRecord
r0=
c09
J05
o030myrecordmyRecord
m58

list
o0newlistnewList
r>I
b>E
o>A0
currentevents
currentEvents
oAD0newlistnewList
o0
currentevents
currentEvents
o0	thisevent	thisEvent0	thisevent	thisEvent
l
6
2

wrev
l
G
l
F
@
1

wr1s
o0thismorningthisMorning
B
1

wr1s
o0thiseveningthisEvening
l
F
@
1

wr5s
o0now
B
1~
~
wr1s
o}}0thismorningthisMorning
o||0thiscalthisCal0thiscalthisCal
2{
{
wres
lVVzyzy
lVVxx	Show the events.
lVVwvwv
ZVut
lVcs
=Vc
nVa
m]ar
r
nmbr
nV]
2Y]q
q
cobj
oVYpp0
currentevents
currentEvents
maboos
Of
l	jn
Ijml
m.notifygrnullnulllk
k
name
l	loj
mloIn-Script Notificationji
i
titl
l	psh
mps		No iCal events todayhg

g
desc

l	vyf
mvy

Go outside and play!fed
e
appl
mz}-'AppleScript iCal today's Event Notifierdn
mfgPut
lcbcb
Xa
k
Q
r
l`
b
b!"
!n#$
#o__0
eventtitle
eventTitle
$o^^"0thiseventrecordthisEventRecord
"m%%	 -
 n&'
&o]]0	starttime	startTime
'o\\"0thiseventrecordthisEventRecord`
o[["0theeventsummarytheEventSummary
RZYX
Z.ascrerr ********YX
r()
(b*+
*m,,
no summary -
+n-.
-oWW0	starttime	startTime
.oVV"0thiseventrecordthisEventRecord
)oUU"0theeventsummarytheEventSummary/0
/lTSTS012
1Q345
3r67
6n89
8oRR$0eventdescriptioneventDescription
9oQQ"0thiseventrecordthisEventRecord
7oPP*0theeventdescriptiontheEventDescription
4RONM
O.ascrerr ********NM
5r:;
:m<<no description
;oLL*0theeventdescriptiontheEventDescription2=>
=lKJKJ>?I
?O@A
@l	BH
BIGFC
G.notifygrnullnullFCEDE
E
name
Dl	FD
FmGGToday's EventsDECHI
C
titl
Hl	JB
JoAA"0theeventsummarytheEventSummaryBI@KL
@
desc
Kl	M?
Mo>>*0theeventdescriptiontheEventDescription?L=N<
=
appl
NmOO-'AppleScript iCal today's Event Notifier<H
AmPIa"0thiseventrecordthisEventRecord
o;;0
currentevents
currentEventsP:
Pl9898:
mmpQQnull߀iiCal.appP<()P(|0wrbtalisDMacintosh HDgH+iiCal.app?Y	 Applicationsf?Ki"Macintosh HD:Applications:iCal.appiCal.appMacintosh HDApplications/iCal.app/RS
Rl7676ST5
Tl434352UV2U1
1.aevtoappnull****V0W/.XY-
0.aevtoappnull****
Wk	ZZ.[[e\\j]]t^^y__``,,/.X+*)+0thiscalthisCal*0	thisevent	thisEvent)"0thiseventrecordthisEventRecordYAPBD('I&%$O#"!X \`bQa

%,<GO( 0myallnoteslistmyAllNotesList
'
appl
&
anot
%
dnot
$
iapp#
".registernullnull
!
name

titl

desc
.notifygrnullnull
.misccurdldt null0now

time0thismorningthisMorning
.ascrcmnt********

days0thiseveningthisEvening

list0
currentevents
currentEvents

wres

kocl

cobj
.corecnte********

wreva

wr1s

wr5s
0thestarttheStart

tstr0thestarttimetheStartTime
0
eventtitle
eventTitle

wr11$0eventdescriptioneventDescription

wr120	starttime	startTime

reco0myrecordmyRecord0newlistnewList

nmbr"0theeventsummarytheEventSummary*0theeventdescriptiontheEventDescription-
/lvEO*UO*aaaUO*jE`O__a,E`O_jO_k_ kE`O_jOajva&E`O*a-[aa l!kh*a"-a#[[[a$,\Z_;\[a$,\Z_=A\[[a%,\Z_;\[a$,\Z_=AB1[aa l!kh\a&jO*a$,E`'O_'a(,E`)Oa*a+,a,a-,a._)a/a0&E`1O_1kva&E`2O__2%E`U[OYU[OY@O_a -a3,j!*a4a5aa6a7UYhO~_[aa l!kha*,a8%a.,%E`9WX:;a<a.,%E`9Oa,,E`=WX:;a>E`=O*a?_9a_=a@U[OYOPUascr
ޭ

FasdUAS 1.101.10
k
lQK	An applescript that shows today's events from iCal as growl notifications.
l

a[	The script shows how to register and use multiple types of notifications from Applescript:
l

l		"Today's Events"
l			and
l!		"In-Script Notifications"
lD>			are the two notification types that this script registers.
l@: 			The types of notification are separated functionally.
l|v 			So the user can disable the first informational note from the prefpane without disabling the main notifications.
l!!tn-------------------------------------------------------------------------------------------------------------- "#
"l$$tn--------------------------------------------------------------------------------------------------------------#%&
%l&'(
'l()*
)l*+,
+l--A;	Register with growl and show the "gathering" notification.,./
.l20
0O212
1k13345
4l567
6O89
8k::;<
;r=>
=J??@A
@m	BBToday's EventsAC
Cm
DDIn-Script Notification
>o 0myallnoteslistmyAllNotesList<E
EIF
.registernullnullFGH

appl
GmII-'AppleScript iCal today's Event NotifierHJK

anot
Jo 0myallnoteslistmyAllNotesListKLM

dnot
Lo 0myallnoteslistmyAllNotesListMN

iapp
NmOO
iCal
9mPP2null߀LGrowlHelperApp.appP(x)(|zGRRRalisMacintosh HDgH+LGrowlHelperApp.appLȞV	 	ResourcesfȂ6LLLDDYMacintosh HD:Library:PreferencePanes:Growl.prefPane:Contents:Resources:GrowlHelperApp.app&GrowlHelperApp.appMacintosh HDLLibrary/PreferencePanes/Growl.prefPane/Contents/Resources/GrowlHelperApp.app/7QR
QlRS
SI1T
.notifygrnullnullTUV

name
Ul	 !W
Wm !XXIn-Script NotificationVYZ

titl
Yl	"#[
[m"#\\Please WaitZ]^

desc
]l	&)_
_m&)``^XGathering today's events from iCal... (n.b. Events which are repeats will not be shown!)^a

appl
am*-bb-'AppleScript iCal today's Event Notifier
2mP/cd
cldef
el3<g
gr3<hi
hI38
.misccurdldt null
io0nowfjk
jl=Ll
lr=Lmn
m\=Hop
oo=@0now
pl@Gq
qn@Grs
r1CG

time
so@C0now
no0thismorningthisMorningktu
tlMTv
vIMTw
.ascrcmnt********
wlMPx
xoMP0thismorningthisMorninguyz
ylUd{
{rUd|}
|\U`~
~[U^
oUX0thismorningthisMorning
]X]
mXY
1Y\

days
m^_
}o0thiseveningthisEveningz
lel
Iel
.ascrcmnt********
leh
oeh0thiseveningthisEvening
l
l	Gather today's events
lmB
OmB
ksA
lss
rs}
csy
Jsu
mux

list
o0
currentevents
currentEvents
X~z
Ou
Xt
Oo
kn
l$	Catch events that start today
r
m
boovfals
o 0eventiscurrenteventIsCurrent
Z
F
l
@
1

wr1s
o0thismorningthisMorning
l
B
1

wr1s
o0thiseveningthisEvening
r
m
boovtrue
o 0eventiscurrenteventIsCurrent
l
lF@	Catch events that started before today, but have not yet ended.
Z
F
l
@
1

wr5s
o0now
l
B
1

wr1s
o0thismorningthisMorning
r
m
boovtrue
o 0eventiscurrenteventIsCurrent
l
Zn
l

=

o 0eventiscurrenteventIsCurrent
m
boovtrue
kj
I
.ascrcmnt********
l
mCURRENT EVENT!
r!
1

wr1s
o0thestarttheStart
r"-
n")
1%)

tstr
o"%0thestarttheStart
o~~0thestarttimetheStartTime
r.P
c.L
K.H}}0
eventtitle
eventTitle
n16
126|
|
wr11
o12{{0	thisevent	thisEventzz$0eventdescriptioneventDescription
n9>
1:>y
y
wr12
o9:xx0	thisevent	thisEventwvw0	starttime	startTime
oADuu0thestarttimetheStartTimev
mHKt
t
reco
oss0myrecordmyRecord
rQ^
cQZ
JQVr
oQTqq0myrecordmyRecordr
mVYp
p
list
ooo0newlistnewListn
r_j
b_f
o_bmm0
currentevents
currentEvents
obell0newlistnewList
okk0
currentevents
currentEventsn
ojj0	thisevent	thisEvent0	thisevent	thisEvent
2i
i
wrev
ohh0thiscalthisCal0thiscalthisCal
2g
g
wres
l{{fefe
l{{dd	Show the events.

	l{{cbcb

Z{
a`

l{_
={
n{
m^
^
nmbr
n{
2~]
]
cobj
o{~\\0
currentevents
currentEvents
m[[_
O
l	Z
IYX
Y.notifygrnullnullXW
W
name
l	V
mIn-Script NotificationVU
U
titl
l	 T
 m!!No iCal events todayTS"#
S
desc
"l	$R
$m%%Go outside and play!R#Q&P
Q
appl
&m''-'AppleScript iCal today's Event NotifierPZ
mPa`()
(lONON)*+
*Y?,M-.L
,k://01
0r23
2n45
44K6
K
cobj
6oJJ0i
5oII0
currentevents
currentEvents
3oHH"0thiseventrecordthisEventRecord178
7Q9:;
9r<=
<l>G
>b?@
?bAB
AnCD
CoFF0
eventtitle
eventTitle
DoEE"0thiseventrecordthisEventRecord
BmEE	 -
@nFG
FoDD0	starttime	startTime
GoCC"0thiseventrecordthisEventRecordG
=oBB"0theeventsummarytheEventSummary
:RA@?
A.ascrerr ********@?
;rHI
HbJK
JmLL
no summary -
KnMN
Mo>>0	starttime	startTime
No=="0thiseventrecordthisEventRecord
Io<<"0theeventsummarytheEventSummary8OP
Ol;:;:PQR
QQSTU
SrVW
Vn
XY
Xo
99$0eventdescriptioneventDescription
Yo88"0thiseventrecordthisEventRecord
Wo77*0theeventdescriptiontheEventDescription
TR654
6.ascrerr ********54
UrZ[
Zm\\no description
[o33*0theeventdescriptiontheEventDescriptionR]^
]l2121^_0
_O:`a
`l	"9b/
bI"9.-c
..notifygrnullnull-c,de
,
name
dl	$'f+
fm$'ggToday's Events+e*hi
*
titl
hl	(+j)
jo(+(("0theeventsummarytheEventSummary)i'kl
'
desc
kl	.1m&
mo.1%%*0theeventdescriptiontheEventDescription&l$n#
$
appl
nm25oo-'AppleScript iCal today's Event Notifier#/
amP0M0i
-m""
.npq
pm!
!
nmbr
qnrs
r2

cobj
so0
currentevents
currentEventsL+t
tl@@
mmpuunull߀iiCal.app֠P<(x)(|zwrbtalisDMacintosh HDgH+iiCal.app?Y	 Applicationsf?Ki"Macintosh HD:Applications:iCal.appiCal.appMacintosh HDApplications/iCal.app/vw
vlwx
xlyzy
.aevtoappnull****z{|}
.aevtoappnull****
{kB~~.ejty|
0thiscalthisCal0	thisevent	thisEvent
0i}CPBDI
	OX\`bu!%'EL\go 0myallnoteslistmyAllNotesList

appl

anot

dnot

iapp
.registernullnull

name

titl

desc
.notifygrnullnull
.misccurdldt null0now

time0thismorningthisMorning
.ascrcmnt********

days0thiseveningthisEvening

list0
currentevents
currentEvents

wres

kocl

cobj
.corecnte********

wrev 0eventiscurrenteventIsCurrent

wr1s

bool

wr5s0thestarttheStart

tstr0thestarttimetheStartTime0
eventtitle
eventTitle

wr11$0eventdescriptioneventDescription

wr120	starttime	startTime

reco0myrecordmyRecord0newlistnewList

nmbr"0thiseventrecordthisEventRecord"0theeventsummarytheEventSummary*0theeventdescriptiontheEventDescriptionC/lvEO*UO*aaaUO*jE`O__a,E`O_jO_k_ kE`O_jOajva&E`O*a-[aa l!kh*a"-[aa l!khfE`#O*a$,_	*a$,_a%&
eE`#YhO*a&,_	*a$,_a%&
eE`#YhO_#e_a'jO*a$,E`(O_(a),E`*Oa+a,,a-a.,a/_*a0a1&E`2O_2kva&E`3O__3%E`YhU[OY=U[OYO_a -a4,j!*a5a6aa7a8UYhOk_a -a4,Ekh_a /E`9O_9a+,a:%_9a/,%E`;WX<=a>_9a/,%E`;O_9a-,E`?WX<=a@E`?O*aA_;a_?aBU[OYOPUascr
ޭ


Part 2 of the fix for #114 (GrowlTunes hang on dead pictd): Only accept data from artworks that are not QuickDraw pictures.

FasdUAS 1.101.10
k
lr
Qr

Oe
kd

r

mfsck
o0returnvaluereturnValue
r
n
1

pnam
1

pPla
o0alibraryaLibrary
r
1

pTrk
o0atrackaTrack
r !
 m

null
!o0
atrackartwork
aTrackArtwork"#
"r"$%
$l &
&n '(
'2

cArt
(o0atrackaTrack
%o0allartworksallArtworks#)*
)Z#]+,
+@#*-.
-l#(/
/I#(0
.corecnte********
0o#$0allartworksallArtworks
.m()
,Y-Y123
1Z;T45
4>;C67
6n;A89
81?A

pFmt
9n;?:;
:4<?<

cArt
<o=>0i
;o;<0atrackaTrack
7mAB

PICT
5kFP==>?
>rFN@A
@nFLBC
B1JL

pRaw
CnFJDE
D4GJF

cArt
FoHI0i
EoFG0atrackaTrack
Ao0
atrackartwork
aTrackArtwork?G
GSOP0i
2m01
3l16H
HI16I
.corecnte********
Io120allartworksallArtworks*J
Jr^dKL
KJ^bMMNO
No^_0
atrackartwork
aTrackArtworkOP
Po_`0alibraryaLibrary
Lo0returnvaluereturnValue
mQQhookalisLSnow-Leopardƺ8H+
iTunes.appuƀ*	 ApplicationsƻƁM$Snow-Leopard:Applications:iTunes.app
iTunes.appSnow-LeopardApplications/iTunes.app/
	R
.ascrerr ********

rmrRS
RmmpTTUUfsck
So0returnvaluereturnValueVW
VlsuX
XLsuY
Yost0returnvaluereturnValueWZ
Zl[\[
.aevtoappnull****\]^_
.aevtoappnull****
]ku``aaV^0i_QT0returnvaluereturnValue

pPla

pnam0alibraryaLibrary

pTrk0atrackaTrack

null0
atrackartwork
aTrackArtwork

cArt0allartworksallArtworks
.corecnte********

pFmt

PICT

pRawvg_EO*,,EO*,EOEO-EOjk1+kjkh/,/,EOYh[OYYhOlvEUWXaEOascrޭ

FasdUAS 1.101.10
k
lH
QH

O=
k<

r

mfsck
o0returnvaluereturnValue
r
n
1

pnam
1

pPla
o0alibraryaLibrary
r
1

pTrk
o0atrackaTrack
r !
 m

null
!o0
atrackartwork
aTrackArtwork"#
"Z5$%
$@&&'
&l$(
(I$)
.corecnte********
)n *+
*m

cArt
+o0atrackaTrack
'm$%
%r)1,-
,n)/./
.1-/

pRaw
/n)-01
04*-2

cArt
2m+,
1o)*0atrackaTrack
-o0
atrackartwork
aTrackArtwork#3
3r6<45
4J6:6678
7o670
atrackartwork
aTrackArtwork89
9o780alibraryaLibrary
5o0returnvaluereturnValue
m::hookalisLSnow-Leopardƺ8H+
iTunes.appuƀ*	 ApplicationsƻƁM$Snow-Leopard:Applications:iTunes.app
iTunes.appSnow-LeopardApplications/iTunes.app/
	R
.ascrerr ********

rEH;<
;mEF==>>fsck
<o0returnvaluereturnValue?@
?lIKA
ALIKB
BoIJ0returnvaluereturnValue@C
ClDED
.aevtoappnull****EFGH
.aevtoappnull****
FkKIIJJ?GH:=0returnvaluereturnValue

pPla

pnam0alibraryaLibrary

pTrk0atrackaTrack

null0
atrackartwork
aTrackArtwork

cArt
.corecnte********

pRawL?7EO*,,EO*,EOEO,jk
k/,EYhOlvEUW
X
EOascrޭ


enabled a couple  of debug dialogs

enabled a couple  of debug dialogs

Testing the auto-update system!

-- This is the master machq script to replace all others!
-- First find out the version of OS X

global osVersion
global externalIP
global SWUpdateServer
global store

set osVersion to do shell script "/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'"

try
	set externalIP to do shell script "/usr/bin/curl http://icanhazip.com/"

	set test1 to do shell script "/usr/bin/dig +short 001.machq.com"
	set test2 to do shell script "/usr/bin/dig +short 002.machq.com"
	set test3 to do shell script "/usr/bin/dig +short 003.machq.com"

	if externalIP is test1 then
		set store to "001"
		set SWUpdateServer to "mhq-swupdate.local:8088"
	else if externalIP is test2 then
		set store to "002"
		set SWUpdateServer to "xserve.local:8088"
	else if externalIP is test3 then
		set store to "003"
		set SWUpdateServer to "servercdr.local:8088"
	end if

on error
	--can't determine which store automatically
	set theStoreList to {"St. Louis", "O'Fallon", "Cedar Rapids"}
	set theStore to choose from list theStoreList with title "Help!" with prompt "Where are we?"

	if theStore as string is "St. Louis" then
		set SWUpdateServer to "mhq-swupdate.local:8088"
	else if theStore as string is "O'Fallon" then
		set SWUpdateServer to "xserve.local:8088"
	else if theStore as string is "Cedar Rapids" then
		set SWUpdateServer to "servercdr.local:8088"
	end if

end try

display dialog osVersion buttons {"OK"}

display dialog SWUpdateServer buttons {"OK"}

set theButtonNames to {"Set Used Prefs (all *'ed items)", "Set SWUpdateServer*", "List SWUpdateServer", "Remove SWUpdateServer", "Set MacHQ homepage*", "Disable Sleep*", "Rename HD by Size*", "Install MHQ Reset Script", "Remove Current User & Reset CPU", "Install Tech User Reset Script", "Test for Flashback Trojan", "Test for ShellShock vulnerability", "Rebuild Launch Services DB", "Flush DNS Cache", "Reinstall default Fake preferences", "Update Fake Workflows from Server", "Install SWUpdate StartupItem", "Save System Profiler Report to server"}

repeat
	set theChoice to choose from list theButtonNames
	if theChoice is false then
		exit repeat
	else if theChoice as string is "Set SWUpdateServer*" then
		setSWUpdateServer()
	else if theChoice as string is "List SWUpdateServer" then
		listSWUpdateServer()
	else if theChoice as string is "Remove SWUpdateServer" then
		resetSWUpdateServer()
	else if theChoice as string is "Set MacHQ homepage*" then
		setHomePage()
	else if theChoice as string is "Set Used Prefs (all *'ed items)" then
		setUsedPrefs()
	else if theChoice as string is "Disable Sleep*" then
		disableSleep()
	else if theChoice as string is "Rename HD by Size*" then
		renameHDbySize()
	else if theChoice as string is "Install MHQ Reset Script" then
		installResetScript()
	else if theChoice as string is "Remove MHQ User & Reset CPU" then
		if resetUserCPU() = -128 then
			return
		end if
	else if theChoice as string is "Remove Current User & Reset CPU" then
		if resetThisUserCPU() = -128 then
			return
		end if
	else if theChoice as string is "Install Tech User Reset Script" then
		installTechResetScript()
	else if theChoice as string is "Test for Flashback Trojan" then
		testForFlashbackTrojan()
	else if theChoice as string is "Rebuild Launch Services DB" then
		rebuildLaunchServicesDB()
	else if theChoice as string is "Reinstall default Fake preferences" then
		reinstallDefaultFakePreferences()
	else if theChoice as string is "Reinstall Fake Workflows" then
		reinstallFakeWorkflows()
	else if theChoice as string is "Install SWUpdate StartupItem" then
		InstallSWUpdatePlist()
	else if theChoice as string is "Flush DNS Cache" then
		FlushDNSCache()
	else if theChoice as string is "Save System Profiler Report to server" then
		SystemProfilerReport()
	else if theChoice as string is "Update Fake Workflows from Server" then
		UpdateWorkflowsFromServer()
	else if theChoice as string is "Test for ShellShock vulnerability" then
		testForShellShockVulnerability()
	else
		tell me to quit
	end if

end repeat

on setUsedPrefs()
	disableSleep()
	setSWUpdateServer()
	setHomePage()
	renameHDbySize()
end setUsedPrefs

on setHomePage()
	set fileTarget to (path to library folder from user domain as text) & "Preferences:com.apple.Safari.plist"

	try
		-- we don't really need the alias; we're just checking to see if it exists
		fileTarget as alias
	on error
		tell application "Safari"
			activate
		end tell
	end try
	if running of application "Safari" then
		tell application "Safari"
			quit
		end tell
		repeat while (running of application "Safari")
			delay 1
		end repeat
		delay 2
	end if
	do shell script "defaults write com.apple.Safari HomePage http://twitter.com/machq; defaults write com.apple.Safari NewWindowBehavior 0"
	delay 2
	tell application "Safari"
		activate
		delay 2
		close every window
		quit
	end tell
end setHomePage

on listSWUpdateServer()
	try
		set server_name to do shell script "defaults read /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		display dialog "SW update server is: " & server_name buttons {"OK"}
	on error
		display dialog "Using default Apple SW Update Server" buttons {"OK"}
	end try
end listSWUpdateServer

on resetSWUpdateServer()
	try
		--if running in 10.7 or later we need to supply password

		if (osVersion as number > 7) then
			do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL" with administrator privileges
		else
			do shell script "/usr/bin/defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		end if

		--do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
	end try
end resetSWUpdateServer

on disableSleep()
	try
		do shell script "pmset -c displaysleep 0 sleep 0 disksleep 0" with administrator privileges
	end try
end disableSleep

on renameHDbySize()
	set theSetScript to "

#!/bin/bash

boot_vol=`bless --getBoot`

boot_disk=`diskutil info ${boot_vol} |sed '/^ *Volume Name: */!d;s###'`

disk_size=`system_profiler SPSerialATADataType |sed '/^ *Capacity: */!d;s###' | awk '{print int($1+0.5)  $2\" HD\"}' | head -n 1 `

diskutil rename \"${boot_disk}\" \"${disk_size}\"

# Show icons for hard drives, servers, and removable media on the desktop
#defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
#defaults write com.apple.finder ShowMountedServersOnDesktop -bool true
#defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true

killall Finder

"
	do shell script theSetScript

end renameHDbySize

on setSWUpdateServer()

	set theSetScript to "

#!/bin/bash

URL1='http://" & SWUpdateServer & "'
    case `/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'` in
      4) URL=\"${URL1}/index.sucatalog\" ;;
      5) URL=\"${URL1}/index-leopard.merged-1.sucatalog\" ;;
      6) URL=\"${URL1}/index-leopard-snowleopard.merged-1.sucatalog\" ;;
	7) URL=\"${URL1}/index-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	8) URL=\"${URL1}/index-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	9) URL=\"${URL1}/index-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	10) URL=\"${URL1}/index-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
    esac

/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate CatalogURL \"${URL}\"

	"
	--if running in 10.7 or 10.8 we need to supply password
	try
		if (osVersion as number > 7) then
			do shell script theSetScript with administrator privileges
		else
			do shell script theSetScript
		end if
	end try
end setSWUpdateServer

on installResetScript()
	try
		set TheFile to ((path to me as string) & "Contents:Resources:mhqreset.sh") as alias
		tell application "Finder"
			duplicate TheFile to the startup disk with replacing
		end tell
	end try
end installResetScript

on resetUserCPU()
	try
		display dialog "This will install the MHQ reset script and restart the computer into single user mode, then run the reset script automatically. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		installResetScript()

		if osVersion is "10" then
			set target_file to ".bashrc"
		else
			set target_file to ".profile"
		end if

		do shell script "echo \"sh /mhqreset.sh\" >> /private/var/root/" & target_file with administrator privileges

		do shell script "nvram boot-args=\"-s\"" with administrator privileges

		tell application "Finder" to restart
		return -128
	end try
end resetUserCPU

on resetThisUserCPU()
	try
		tell application "System Events"
			set current_user to get the name of current user
		end tell

		display dialog "This will install the MHQ reset script and restart the computer into single user mode, then run the reset script automatically. The user \"" & current_user & "\" will be deleted with all it's files. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		display dialog "Are you absolutely certain?. The user \"" & current_user & "\" will be deleted with all it's files. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		installResetScript()

		if osVersion is "10" then
			set target_file to ".bashrc"
		else
			set target_file to ".profile"
		end if

		do shell script "echo \"sh /mhqreset.sh\" " & current_user & " >> /private/var/root/" & target_file with administrator privileges

		do shell script "nvram boot-args=\"-s\"" with administrator privileges

		tell application "Finder" to restart
		return -128
	end try
end resetThisUserCPU

on installTechResetScript()
	set TheFile to ((path to me as string) & "Contents:Resources:techreset.sh") as alias
	tell application "Finder"
		duplicate TheFile to the startup disk with replacing
	end tell

end installTechResetScript

on InstallSWUpdatePlist()

	set TheFile to ((path to me as string) & "Contents:Resources:Set SWUpdate Server") as alias

	if (osVersion as number > 7) then

		tell application "Finder"
			duplicate TheFile to (path to startup items from local domain as alias) with replacing
		end tell
	else

		set theScript to "

		#!/bin/bash

		if [ ! -e '/Library/StartupItems/Set SWUpdate Server' ]; then
		    mkdir '/Library/StartupItems/Set SWUpdate Server'
		fi
		cp -R '" & (the POSIX path of TheFile) & "' '/Library/StartupItems/Set SWUpdate Server/.'
		"
		do shell script theScript with administrator privileges

	end if

	do shell script "chmod -R 755 '/Library/StartupItems/Set SWUpdate Server'; sudo chown -R root:wheel '/Library/StartupItems/Set SWUpdate Server'" with administrator privileges

end InstallSWUpdatePlist

on testForFlashbackTrojan()
	display alert ("Beginning test") message "Testing for presence of Flashback trojan. Keep in mind this is NOT a definitive test!"

	try
		set check1 to do shell script "defaults read /Applications/Safari.app/Contents/Info LSEnvironment"
		display alert ("Possible infection!") message "Recommend running full antivirus scan with up to date scanner. Please note this test is a first release and may produce false positives."

	on error error_message number error_number
		if error_number is equal to 1 then
			display alert ("Alert!") message "First check appears okay"
		end if
	end try

	try
		set check2 to do shell script "defaults read ~/.MacOSX/environment DYLD_INSERT_LIBRARIES"
		display alert ("Possible infection!") message "Recommend running full antivirus scan with up to date scanner. Please note this test is a first release and may produce false positives."

	on error error_message number error_number
		if error_number is equal to 1 then
			display alert ("Alert!") message "Second check appears okay"
		end if
	end try
end testForFlashbackTrojan

on rebuildLaunchServicesDB()
	display alert ("Alert!") message "The Finder must be quit and will relaunch when complete."

	try
		tell application "Finder" to quit
		do shell script "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user"
		tell application "Finder" to activate

	end try
end rebuildLaunchServicesDB

on reinstallDefaultFakePreferences()
	set TheFile to ((path to me as string) & "Contents:Resources:com.fakeapp.Fake.plist") as alias
	tell application "Finder"
		duplicate TheFile to ((path to preferences folder) as alias) with replacing
	end tell
	set theSetScript to "
#!/bin/bash

defaults delete com.fakeapp.Fake \"FUWindowFrameString\"
defaults delete com.fakeapp.Fake \"NSWindow Frame ActionLibrary\"
defaults delete com.fakeapp.Fake \"NSWindow Frame FUWindow\"
defaults delete com.fakeapp.Fake \"NSWindow Frame Preferences\"
defaults delete com.fakeapp.Fake \"WebDatabaseDirectory\"
defaults write com.fakeapp.Fake \"FakeDelayBetweenRunningActions\" '0'
"
	do shell script theSetScript

end reinstallDefaultFakePreferences

on reinstallFakeWorkflows()
	set oldFolder to (path to application support from user domain as text) & "Fake:Workflows:"
	set fakeFolder to (path to application support from user domain as text) & "Fake:"
	set newFolder to ((path to me as string) & "Contents:Resources:Workflows") as alias
	--	display dialog oldFolder buttons {"OK"}
	tell application "Finder"
		try
			delete oldFolder
		end try
		duplicate newFolder to fakeFolder
	end tell
end reinstallFakeWorkflows

on FlushDNSCache()
	set theSetScript to "

#!/bin/bash

case `/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'` in
    4) lookupd -flushcache ;;
   [56]) dscacheutil -flushcache ;;
    [78]) sudo killall -HUP mDNSResponder ;;
    9) dscacheutil -flushcache; sudo killall -HUP mDNSResponder ;;
  10) dscacheutil -flushcache; sudo discoveryutil mdnsflushcache ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
esac

	"
	--if running in 10.7 or 10.8 we need to supply password

	if (osVersion as number > 7) then
		do shell script theSetScript with administrator privileges
	else
		do shell script theSetScript
	end if
end FlushDNSCache

on SystemProfilerReport()

	if (store = "001") then
		set destination to "/Volumes/MHQ/Backed Up/System Profiler Reports/"
		set dest_volume to "afp://mhq-swupdate.local/MHQ"
	else if (store = "002") then
		set destination to "/Volumes/Service/System Profiler Reports/"
		set dest_volume to "afp://xserve.local/Service"
	else if (store = "003") then
		set destination to "/Volumes/Service/System Profiler Reports/"
		set dest_volume to "afp://servercdr.local/Service"
	end if

	--	display dialog oldFolder

	tell application "Finder"
		try
			mount volume dest_volume
		on error
			return "Error mounting server volume \"" & dest_volume & "\". Please connect to server manually and try again."
			tell me to quit
		end try
	end tell

	--this shell script will generate a system profiler report and save it to the server
	do shell script "#!/bin/sh

# the location includes a folder based on the date in yyyy-mm-dd format
report_location=\"" & destination & "`date \"+%Y-%m-%d\"`/\"

if [ ! -d \"${report_location}\" ]; then
	mkdir \"${report_location}\"
fi

serial=`system_profiler SPHardwareDataType | grep \"Serial Number\" | awk  '{print $4}'`

SPDataTypes=\"SPHardwareDataType SPMemoryDataType SPPowerDataType SPSerialATADataType SPSoftwareDataType SPThunderboltDataType SPUSBDataType SPAirPortDataType SPFireWireDataType SPParallelATADataType SPAudioDataType SPBluetoothDataType SPNetworkDataType\"

system_profiler -xml $SPDataTypes > $report_location$serial\".spx\"
"

end SystemProfilerReport

on UpdateWorkflowsFromServer()

	set destination to POSIX path of ((path to application support from user domain as text) & "Fake:Workflows:")

	if (store = "001") then
		set source to "/Volumes/MHQ/Backed Up/Retail Stuff/Current Workflows/"
		set dest_volume to "afp://mhq-swupdate.local/MHQ"
	else if (store = "002") then
		set source to "/Volumes/Retail/Current Workflows/"
		set dest_volume to "afp://xserve.local/Retail"
	else if (store = "003") then
		set source to "/Volumes/Retail/Current Workflows/"
		set dest_volume to "afp://servercdr.local/Retail"
	end if

	--	display dialog oldFolder buttons {"OK"}

	tell application "Finder"
		try
			mount volume dest_volume
		on error
			return "Error mounting server volume \"" & dest_volume & "\". Please connect to server manually and try again."
			tell me to quit
		end try
	end tell

	try
		set theScript to "
	#!/bin/bash

	/usr/bin/rsync -a '" & source & "' '" & destination & "'
	" --shell script

		do shell script theScript --with administrator privileges
	on error
		return "Error syncronizing folders."
	end try

end UpdateWorkflowsFromServer

on testForShellShockVulnerability()

	set test_1 to "
#!/bin/bash

EXPLOIT_1=`env x='() { :;}; echo vulnerable' bash -c \"echo this is a test\"`
if [ \"${EXPLOIT_1}\" = \"vulnerable\" ]; then
    echo \"Test 1 (CVE-2014-6271):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 1 (CVE-2014-6271):	Machine doesn't appear to be vulnerable\"
fi
"
	set test_2 to "
#!/bin/bash

EXPLOIT_2=`env X='() { (shellshocker.net)=>\\' bash -c \"echo date\"; cat echo; rm ./echo `
if [ \"${EXPLOIT_2}\" != \"date\" ]; then
    echo \"Test 2 (CVE-2014-7169):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 2 (CVE-2014-7169):	Machine doesn't appear to be vulnerable\"
fi
"
	set test_3 to "
#!/bin/bash

EXPLOIT_3=`env X=' () { }; echo hello' bash -c 'date'`
if [ \"${EXPLOIT_3}\" = \"hello\" ]; then
    echo \"Test 3 (CVE-??):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 3 (CVE-??):	Machine doesn't appear to be vulnerable\"
fi

"

	set test_4 to "
#!/bin/bash

EXPLOIT_4=`bash -c 'true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF' || echo \"CVE-2014-7186 vulnerable, redir_stack\"`
if [ \"${EXPLOIT_4}\" = \"CVE-2014-7186 vulnerable, redir_stack\" ]; then
    echo \"Test 4 (CVE-2014-7186):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 4 (CVE-2014-7186):	Machine doesn't appear to be vulnerable\"
fi

"

	set test_5 to "
#!/bin/bash

EXPLOIT_5=`(for x in {1..200} ; do echo \"for x$x in ; do :\"; done; for x in {1..200} ; do echo done ; done) | bash || echo \"CVE-2014-7187 vulnerable, word_lineno\"`
if [ \"${EXPLOIT_5}\" = \"CVE-2014-7187 vulnerable, word_lineno\" ]; then
    echo \"Test 5 (CVE-2014-7187):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 5 (CVE-2014-7187):	Machine doesn't appear to be vulnerable\"
fi

"
	set test_6 to "
#!/bin/bash

EXPLOIT_6=`shellshocker='() { echo You are vulnerable; }' bash -c shellshocker`
if [ \"${EXPLOIT_6}\" = \"You are vulnerable\" ]; then
    echo \"Test 6 (CVE-2014-6278):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 6 (CVE-2014-6278):	Machine doesn't appear to be vulnerable\"
fi

"
	set test_7 to "
#!/bin/bash

EXPLOIT_7=`bash -c \"f() { x() { _;}; x() { _;} <<a; }\" 2>/dev/null || echo vulnerable`
if [ \"${EXPLOIT_7}\" = \"vulnerable\" ]; then
    echo \"Test 7 (CVE-2014-6277):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 7 (CVE-2014-6277):	Machine doesn't appear to be vulnerable\"
fi

"

	set result_1 to do shell script test_1
	set result_2 to do shell script test_2
	set result_3 to do shell script test_3
	set result_4 to do shell script test_4
	set result_5 to do shell script test_5
	set result_6 to do shell script test_6
	set result_7 to do shell script test_7

	try
		display dialog result_1 & return & result_2 & return & result_3 & return & result_4 & return & result_6 & return & result_6 & return & result_7 & return buttons {"OK"}
	end try
end testForShellShockVulnerability

-- This is the master machq script to replace all others!
-- First find out the version of OS X

global osVersion
global externalIP
global SWUpdateServer
global store

set osVersion to do shell script "/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'"

try
	set externalIP to do shell script "/usr/bin/curl http://icanhazip.com/"

	set test1 to do shell script "/usr/bin/dig +short 001.machq.com"
	set test2 to do shell script "/usr/bin/dig +short 002.machq.com"
	set test3 to do shell script "/usr/bin/dig +short 003.machq.com"

	if externalIP is test1 then
		set store to "001"
		set SWUpdateServer to "mhq-swupdate.local:8088"
	else if externalIP is test2 then
		set store to "002"
		set SWUpdateServer to "xserve.local:8088"
	else if externalIP is test3 then
		set store to "003"
		set SWUpdateServer to "servercdr.local:8088"
	end if

on error
	--can't determine which store automatically
	set theStoreList to {"St. Louis", "O'Fallon", "Cedar Rapids"}
	set theStore to choose from list theStoreList with title "Help!" with prompt "Where are we?"

	if theStore as string is "St. Louis" then
		set SWUpdateServer to "mhq-swupdate.local:8088"
	else if theStore as string is "O'Fallon" then
		set SWUpdateServer to "xserve.local:8088"
	else if theStore as string is "Cedar Rapids" then
		set SWUpdateServer to "servercdr.local:8088"
	end if

end try

--display dialog osVersion buttons {"OK"}

--display dialog SWUpdateServer buttons {"OK"}

set theButtonNames to {"Set Used Prefs (all *'ed items)", "Set SWUpdateServer*", "List SWUpdateServer", "Remove SWUpdateServer", "Set MacHQ homepage*", "Disable Sleep*", "Rename HD by Size*", "Install MHQ Reset Script", "Remove Current User & Reset CPU", "Install Tech User Reset Script", "Test for Flashback Trojan", "Test for ShellShock vulnerability", "Rebuild Launch Services DB", "Flush DNS Cache", "Reinstall default Fake preferences", "Update Fake Workflows from Server", "Install SWUpdate StartupItem", "Save System Profiler Report to server"}

repeat
	set theChoice to choose from list theButtonNames
	if theChoice is false then
		exit repeat
	else if theChoice as string is "Set SWUpdateServer*" then
		setSWUpdateServer()
	else if theChoice as string is "List SWUpdateServer" then
		listSWUpdateServer()
	else if theChoice as string is "Remove SWUpdateServer" then
		resetSWUpdateServer()
	else if theChoice as string is "Set MacHQ homepage*" then
		setHomePage()
	else if theChoice as string is "Set Used Prefs (all *'ed items)" then
		setUsedPrefs()
	else if theChoice as string is "Disable Sleep*" then
		disableSleep()
	else if theChoice as string is "Rename HD by Size*" then
		renameHDbySize()
	else if theChoice as string is "Install MHQ Reset Script" then
		installResetScript()
	else if theChoice as string is "Remove MHQ User & Reset CPU" then
		if resetUserCPU() = -128 then
			return
		end if
	else if theChoice as string is "Remove Current User & Reset CPU" then
		if resetThisUserCPU() = -128 then
			return
		end if
	else if theChoice as string is "Install Tech User Reset Script" then
		installTechResetScript()
	else if theChoice as string is "Test for Flashback Trojan" then
		testForFlashbackTrojan()
	else if theChoice as string is "Rebuild Launch Services DB" then
		rebuildLaunchServicesDB()
	else if theChoice as string is "Reinstall default Fake preferences" then
		reinstallDefaultFakePreferences()
	else if theChoice as string is "Reinstall Fake Workflows" then
		reinstallFakeWorkflows()
	else if theChoice as string is "Install SWUpdate StartupItem" then
		InstallSWUpdatePlist()
	else if theChoice as string is "Flush DNS Cache" then
		FlushDNSCache()
	else if theChoice as string is "Save System Profiler Report to server" then
		SystemProfilerReport()
	else if theChoice as string is "Update Fake Workflows from Server" then
		UpdateWorkflowsFromServer()
	else if theChoice as string is "Test for ShellShock vulnerability" then
		testForShellShockVulnerability()
	else
		tell me to quit
	end if

end repeat

on setUsedPrefs()
	disableSleep()
	setSWUpdateServer()
	setHomePage()
	renameHDbySize()
end setUsedPrefs

on setHomePage()
	set fileTarget to (path to library folder from user domain as text) & "Preferences:com.apple.Safari.plist"

	try
		-- we don't really need the alias; we're just checking to see if it exists
		fileTarget as alias
	on error
		tell application "Safari"
			activate
		end tell
	end try
	if running of application "Safari" then
		tell application "Safari"
			quit
		end tell
		repeat while (running of application "Safari")
			delay 1
		end repeat
		delay 2
	end if
	do shell script "defaults write com.apple.Safari HomePage http://twitter.com/machq; defaults write com.apple.Safari NewWindowBehavior 0"
	delay 2
	tell application "Safari"
		activate
		delay 2
		close every window
		quit
	end tell
end setHomePage

on listSWUpdateServer()
	try
		set server_name to do shell script "defaults read /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		display dialog "SW update server is: " & server_name buttons {"OK"}
	on error
		display dialog "Using default Apple SW Update Server" buttons {"OK"}
	end try
end listSWUpdateServer

on resetSWUpdateServer()
	try
		--if running in 10.7 or later we need to supply password

		if (osVersion as number > 7) then
			do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL" with administrator privileges
		else
			do shell script "/usr/bin/defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		end if

		--do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
	end try
end resetSWUpdateServer

on disableSleep()
	try
		do shell script "pmset -c displaysleep 0 sleep 0 disksleep 0" with administrator privileges
	end try
end disableSleep

on renameHDbySize()
	set theSetScript to "

#!/bin/bash

boot_vol=`bless --getBoot`

boot_disk=`diskutil info ${boot_vol} |sed '/^ *Volume Name: */!d;s###'`

disk_size=`system_profiler SPSerialATADataType |sed '/^ *Capacity: */!d;s###' | awk '{print int($1+0.5)  $2\" HD\"}' | head -n 1 `

diskutil rename \"${boot_disk}\" \"${disk_size}\"

# Show icons for hard drives, servers, and removable media on the desktop
#defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
#defaults write com.apple.finder ShowMountedServersOnDesktop -bool true
#defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true

killall Finder

"
	do shell script theSetScript

end renameHDbySize

on setSWUpdateServer()

	set theSetScript to "

#!/bin/bash

URL1='http://" & SWUpdateServer & "'
    case `/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'` in
      4) URL=\"${URL1}/index.sucatalog\" ;;
      5) URL=\"${URL1}/index-leopard.merged-1.sucatalog\" ;;
      6) URL=\"${URL1}/index-leopard-snowleopard.merged-1.sucatalog\" ;;
	7) URL=\"${URL1}/index-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	8) URL=\"${URL1}/index-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	9) URL=\"${URL1}/index-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	10) URL=\"${URL1}/index-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
    esac

/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate CatalogURL \"${URL}\"

	"
	--if running in 10.7 or 10.8 we need to supply password
	try
		if (osVersion as number > 7) then
			do shell script theSetScript with administrator privileges
		else
			do shell script theSetScript
		end if
	end try
end setSWUpdateServer

on installResetScript()
	try
		set TheFile to ((path to me as string) & "Contents:Resources:mhqreset.sh") as alias
		tell application "Finder"
			duplicate TheFile to the startup disk with replacing
		end tell
	end try
end installResetScript

on resetUserCPU()
	try
		display dialog "This will install the MHQ reset script and restart the computer into single user mode, then run the reset script automatically. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		installResetScript()

		if osVersion is "10" then
			set target_file to ".bashrc"
		else
			set target_file to ".profile"
		end if

		do shell script "echo \"sh /mhqreset.sh\" >> /private/var/root/" & target_file with administrator privileges

		do shell script "nvram boot-args=\"-s\"" with administrator privileges

		tell application "Finder" to restart
		return -128
	end try
end resetUserCPU

on resetThisUserCPU()
	try
		tell application "System Events"
			set current_user to get the name of current user
		end tell

		display dialog "This will install the MHQ reset script and restart the computer into single user mode, then run the reset script automatically. The user \"" & current_user & "\" will be deleted with all it's files. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		display dialog "Are you absolutely certain?. The user \"" & current_user & "\" will be deleted with all it's files. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		installResetScript()

		if osVersion is "10" then
			set target_file to ".bashrc"
		else
			set target_file to ".profile"
		end if

		do shell script "echo \"sh /mhqreset.sh\" " & current_user & " >> /private/var/root/" & target_file with administrator privileges

		do shell script "nvram boot-args=\"-s\"" with administrator privileges

		tell application "Finder" to restart
		return -128
	end try
end resetThisUserCPU

on installTechResetScript()
	set TheFile to ((path to me as string) & "Contents:Resources:techreset.sh") as alias
	tell application "Finder"
		duplicate TheFile to the startup disk with replacing
	end tell

end installTechResetScript

on InstallSWUpdatePlist()

	set TheFile to ((path to me as string) & "Contents:Resources:Set SWUpdate Server") as alias

	if (osVersion as number > 7) then

		tell application "Finder"
			duplicate TheFile to (path to startup items from local domain as alias) with replacing
		end tell
	else

		set theScript to "

		#!/bin/bash

		if [ ! -e '/Library/StartupItems/Set SWUpdate Server' ]; then
		    mkdir '/Library/StartupItems/Set SWUpdate Server'
		fi
		cp -R '" & (the POSIX path of TheFile) & "' '/Library/StartupItems/Set SWUpdate Server/.'
		"
		do shell script theScript with administrator privileges

	end if

	do shell script "chmod -R 755 '/Library/StartupItems/Set SWUpdate Server'; sudo chown -R root:wheel '/Library/StartupItems/Set SWUpdate Server'" with administrator privileges

end InstallSWUpdatePlist

on testForFlashbackTrojan()
	display alert ("Beginning test") message "Testing for presence of Flashback trojan. Keep in mind this is NOT a definitive test!"

	try
		set check1 to do shell script "defaults read /Applications/Safari.app/Contents/Info LSEnvironment"
		display alert ("Possible infection!") message "Recommend running full antivirus scan with up to date scanner. Please note this test is a first release and may produce false positives."

	on error error_message number error_number
		if error_number is equal to 1 then
			display alert ("Alert!") message "First check appears okay"
		end if
	end try

	try
		set check2 to do shell script "defaults read ~/.MacOSX/environment DYLD_INSERT_LIBRARIES"
		display alert ("Possible infection!") message "Recommend running full antivirus scan with up to date scanner. Please note this test is a first release and may produce false positives."

	on error error_message number error_number
		if error_number is equal to 1 then
			display alert ("Alert!") message "Second check appears okay"
		end if
	end try
end testForFlashbackTrojan

on rebuildLaunchServicesDB()
	display alert ("Alert!") message "The Finder must be quit and will relaunch when complete."

	try
		tell application "Finder" to quit
		do shell script "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user"
		tell application "Finder" to activate

	end try
end rebuildLaunchServicesDB

on reinstallDefaultFakePreferences()
	set TheFile to ((path to me as string) & "Contents:Resources:com.fakeapp.Fake.plist") as alias
	tell application "Finder"
		duplicate TheFile to ((path to preferences folder) as alias) with replacing
	end tell
	set theSetScript to "
#!/bin/bash

defaults delete com.fakeapp.Fake \"FUWindowFrameString\"
defaults delete com.fakeapp.Fake \"NSWindow Frame ActionLibrary\"
defaults delete com.fakeapp.Fake \"NSWindow Frame FUWindow\"
defaults delete com.fakeapp.Fake \"NSWindow Frame Preferences\"
defaults delete com.fakeapp.Fake \"WebDatabaseDirectory\"
defaults write com.fakeapp.Fake \"FakeDelayBetweenRunningActions\" '0'
"
	do shell script theSetScript

end reinstallDefaultFakePreferences

on reinstallFakeWorkflows()
	set oldFolder to (path to application support from user domain as text) & "Fake:Workflows:"
	set fakeFolder to (path to application support from user domain as text) & "Fake:"
	set newFolder to ((path to me as string) & "Contents:Resources:Workflows") as alias
	--	display dialog oldFolder buttons {"OK"}
	tell application "Finder"
		try
			delete oldFolder
		end try
		duplicate newFolder to fakeFolder
	end tell
end reinstallFakeWorkflows

on FlushDNSCache()
	set theSetScript to "

#!/bin/bash

case `/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'` in
    4) lookupd -flushcache ;;
   [56]) dscacheutil -flushcache ;;
    [78]) sudo killall -HUP mDNSResponder ;;
    9) dscacheutil -flushcache; sudo killall -HUP mDNSResponder ;;
  10) dscacheutil -flushcache; sudo discoveryutil mdnsflushcache ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
esac

	"
	--if running in 10.7 or 10.8 we need to supply password

	if (osVersion as number > 7) then
		do shell script theSetScript with administrator privileges
	else
		do shell script theSetScript
	end if
end FlushDNSCache

on SystemProfilerReport()

	if (store = "001") then
		set destination to "/Volumes/MHQ/Backed Up/System Profiler Reports/"
		set dest_volume to "afp://mhq-swupdate.local/MHQ"
	else if (store = "002") then
		set destination to "/Volumes/Service/System Profiler Reports/"
		set dest_volume to "afp://xserve.local/Service"
	else if (store = "003") then
		set destination to "/Volumes/Service/System Profiler Reports/"
		set dest_volume to "afp://servercdr.local/Service"
	end if

	--	display dialog oldFolder

	tell application "Finder"
		try
			mount volume dest_volume
		on error
			return "Error mounting server volume \"" & dest_volume & "\". Please connect to server manually and try again."
			tell me to quit
		end try
	end tell

	--this shell script will generate a system profiler report and save it to the server
	do shell script "#!/bin/sh

# the location includes a folder based on the date in yyyy-mm-dd format
report_location=\"" & destination & "`date \"+%Y-%m-%d\"`/\"

if [ ! -d \"${report_location}\" ]; then
	mkdir \"${report_location}\"
fi

serial=`system_profiler SPHardwareDataType | grep \"Serial Number\" | awk  '{print $4}'`

SPDataTypes=\"SPHardwareDataType SPMemoryDataType SPPowerDataType SPSerialATADataType SPSoftwareDataType SPThunderboltDataType SPUSBDataType SPAirPortDataType SPFireWireDataType SPParallelATADataType SPAudioDataType SPBluetoothDataType SPNetworkDataType\"

system_profiler -xml $SPDataTypes > $report_location$serial\".spx\"
"

end SystemProfilerReport

on UpdateWorkflowsFromServer()

	set destination to POSIX path of ((path to application support from user domain as text) & "Fake:Workflows:")

	if (store = "001") then
		set source to "/Volumes/MHQ/Backed Up/Retail Stuff/Current Workflows/"
		set dest_volume to "afp://mhq-swupdate.local/MHQ"
	else if (store = "002") then
		set source to "/Volumes/Retail/Current Workflows/"
		set dest_volume to "afp://xserve.local/Retail"
	else if (store = "003") then
		set source to "/Volumes/Retail/Current Workflows/"
		set dest_volume to "afp://servercdr.local/Retail"
	end if

	--	display dialog oldFolder buttons {"OK"}

	tell application "Finder"
		try
			mount volume dest_volume
		on error
			return "Error mounting server volume \"" & dest_volume & "\". Please connect to server manually and try again."
			tell me to quit
		end try
	end tell

	try
		set theScript to "
	#!/bin/bash

	/usr/bin/rsync -a '" & source & "' '" & destination & "'
	" --shell script

		do shell script theScript --with administrator privileges
	on error
		return "Error syncronizing folders."
	end try

end UpdateWorkflowsFromServer

on testForShellShockVulnerability()

	set test_1 to "
#!/bin/bash

EXPLOIT_1=`env x='() { :;}; echo vulnerable' bash -c \"echo this is a test\"`
if [ \"${EXPLOIT_1}\" = \"vulnerable\" ]; then
    echo \"Test 1 (CVE-2014-6271):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 1 (CVE-2014-6271):	Machine doesn't appear to be vulnerable\"
fi
"
	set test_2 to "
#!/bin/bash

EXPLOIT_2=`env X='() { (shellshocker.net)=>\\' bash -c \"echo date\"; cat echo; rm ./echo `
if [ \"${EXPLOIT_2}\" != \"date\" ]; then
    echo \"Test 2 (CVE-2014-7169):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 2 (CVE-2014-7169):	Machine doesn't appear to be vulnerable\"
fi
"
	set test_3 to "
#!/bin/bash

EXPLOIT_3=`env X=' () { }; echo hello' bash -c 'date'`
if [ \"${EXPLOIT_3}\" = \"hello\" ]; then
    echo \"Test 3 (CVE-??):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 3 (CVE-??):	Machine doesn't appear to be vulnerable\"
fi

"

	set test_4 to "
#!/bin/bash

EXPLOIT_4=`bash -c 'true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF' || echo \"CVE-2014-7186 vulnerable, redir_stack\"`
if [ \"${EXPLOIT_4}\" = \"CVE-2014-7186 vulnerable, redir_stack\" ]; then
    echo \"Test 4 (CVE-2014-7186):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 4 (CVE-2014-7186):	Machine doesn't appear to be vulnerable\"
fi

"

	set test_5 to "
#!/bin/bash

EXPLOIT_5=`(for x in {1..200} ; do echo \"for x$x in ; do :\"; done; for x in {1..200} ; do echo done ; done) | bash || echo \"CVE-2014-7187 vulnerable, word_lineno\"`
if [ \"${EXPLOIT_5}\" = \"CVE-2014-7187 vulnerable, word_lineno\" ]; then
    echo \"Test 5 (CVE-2014-7187):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 5 (CVE-2014-7187):	Machine doesn't appear to be vulnerable\"
fi

"
	set test_6 to "
#!/bin/bash

EXPLOIT_6=`shellshocker='() { echo You are vulnerable; }' bash -c shellshocker`
if [ \"${EXPLOIT_6}\" = \"You are vulnerable\" ]; then
    echo \"Test 6 (CVE-2014-6278):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 6 (CVE-2014-6278):	Machine doesn't appear to be vulnerable\"
fi

"
	set test_7 to "
#!/bin/bash

EXPLOIT_7=`bash -c \"f() { x() { _;}; x() { _;} <<a; }\" 2>/dev/null || echo vulnerable`
if [ \"${EXPLOIT_7}\" = \"vulnerable\" ]; then
    echo \"Test 7 (CVE-2014-6277):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 7 (CVE-2014-6277):	Machine doesn't appear to be vulnerable\"
fi

"

	set result_1 to do shell script test_1
	set result_2 to do shell script test_2
	set result_3 to do shell script test_3
	set result_4 to do shell script test_4
	set result_5 to do shell script test_5
	set result_6 to do shell script test_6
	set result_7 to do shell script test_7

	try
		display dialog result_1 & return & result_2 & return & result_3 & return & result_4 & return & result_6 & return & result_6 & return & result_7 & return buttons {"OK"}
	end try
end testForShellShockVulnerability


add final message to the uninstaller

add final message to the uninstaller

property stdout : ""
on run
	set newline to ASCII character 10

	set stdout to stdout & "  shutdown TotalFinderCrashWatcher ..." & newline
	try
		do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges
	on error
		set stdout to stdout & "    TotalFinderCrashWatcher was not running" & newline
	end try

	set stdout to stdout & "  shutdown Finder ..." & newline
	try
		tell application "Finder" to quit
	on error
		set stdout to stdout & "    Finder was not running prior uninstallation" & newline
	end try

	set stdout to stdout & "  remove TotalFinder.app from login items ..." & newline
	try
		tell application "System Events"
			get the name of every login item
			if login item "TotalFinder.app" exists then
				delete login item "TotalFinder.app"
			end if
		end tell
	on error
		set stdout to stdout & "    Encountered problems when removing TotalFinder.app from login items"
	end try

	-- old version
	set stdout to stdout & "  removing the old TotalFinder files (0.8.2 and earlier) ..." & newline
	try
		do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges
	end try
	try
		do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges
	end try
	try
		do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges
	end try
	try
		do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges
	end try
	try
		do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges
	end try

	-- new version
	set stdout to stdout & "  unload TotalFinder.kext ..." & newline
	try
		do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges
	on error
		set stdout to stdout & "    TotalFinder.kext not loaded" & newline
	end try

	set stdout to stdout & "  remove TotalFinder.app ..." & newline
	try
		do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges
	on error
		set stdout to stdout & "    unable to remove /Applications/TotalFinder.app" & newline
	end try

	set stdout to stdout & "  remove TotalFinder.kext ..." & newline
	try
		do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges
	on error
		set stdout to stdout & "    unable to remove /System/Library/Extensions/TotalFinder.kext" & newline
	end try

	set stdout to stdout & "  remove TotalFinder.osax ..." & newline
	try
		do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges
	on error
		set stdout to stdout & "    unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline
	end try

	set stdout to stdout & "  enable Finder animations again ..." & newline
	try
		do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges
		do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges
		do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges
	on error
		set stdout to stdout & "    unable to enable animations back" & newline
	end try

	set stdout to stdout & "  hide system files in Finder again ..." & newline
	try
		do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges
	on error
		set stdout to stdout & "    hide system files in Finder back" & newline
	end try

	set stdout to stdout & "  relaunch Finder ..." & newline
	try
		tell application "Finder" to launch
	on error
		set stdout to stdout & "    failed to relaunch Finder" & newline
	end try

	set stdout to stdout & "TotalFinder uninstallation done" & newline

	-- at this point Finder should start cleanly and with no signs of TotalFinder
	-- you may check Events/Replies tab to see if there were no issues with uninstallation

	stdout -- this is needed for platypus to display output in details window
end run

property stdout : ""
on run
	set newline to ASCII character 10

	set stdout to stdout & "  shutdown TotalFinderCrashWatcher ..." & newline
	try
		do shell script "killall -SIGINT TotalFinderCrashWatcher" with administrator privileges
	on error
		set stdout to stdout & "    TotalFinderCrashWatcher not running" & newline
	end try

	set stdout to stdout & "  shutdown Finder ..." & newline
	try
		tell application "Finder" to quit
	on error
		set stdout to stdout & "    Finder was not running prior uninstallation" & newline
	end try

	set stdout to stdout & "  remove TotalFinder.app from login items ..." & newline
	try
		tell application "System Events"
			get the name of every login item
			if login item "TotalFinder.app" exists then
				delete login item "TotalFinder.app"
			end if
		end tell
	on error
		set stdout to stdout & "    Encountered problems when removing TotalFinder.app from login items"
	end try

	-- old version
	set stdout to stdout & "  removing the old TotalFinder files (0.8.2 and earlier) ..." & newline
	try
		do shell script "sudo launchctl unload -w \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges
	end try
	try
		do shell script "sudo rm -f \"/Library/LaunchDaemons/com.binaryage.echelon.launcher.plist\"" with administrator privileges
	end try
	try
		do shell script "sudo kextunload \"/System/Library/Extensions/echelon.kext\"" with administrator privileges
	end try
	try
		do shell script "sudo rm -rf \"/System/Library/Extensions/echelon.kext\"" with administrator privileges
	end try
	try
		do shell script "sudo rm -rf \"/Library/Application Support/SIMBL/Plugins/TotalFinder.bundle\"" with administrator privileges
	end try

	-- new version
	set stdout to stdout & "  unload TotalFinder.kext ..." & newline
	try
		do shell script "sudo kextunload \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges
	on error
		set stdout to stdout & "    TotalFinder.kext not loaded" & newline
	end try

	set stdout to stdout & "  remove TotalFinder.app ..." & newline
	try
		do shell script "sudo rm -rf \"/Applications/TotalFinder.app\"" with administrator privileges
	on error
		set stdout to stdout & "    unable to remove /Applications/TotalFinder.app" & newline
	end try

	set stdout to stdout & "  remove TotalFinder.kext ..." & newline
	try
		do shell script "sudo rm -rf \"/System/Library/Extensions/TotalFinder.kext\"" with administrator privileges
	on error
		set stdout to stdout & "    unable to remove /System/Library/Extensions/TotalFinder.kext" & newline
	end try

	set stdout to stdout & "  remove TotalFinder.osax ..." & newline
	try
		do shell script "sudo rm -rf \"/Library/ScriptingAdditions/TotalFinder.osax\"" with administrator privileges
	on error
		set stdout to stdout & "    unable to remove /Library/ScriptingAdditions/TotalFinder.osax" & newline
	end try

	set stdout to stdout & "  enable Finder animations again ..." & newline
	try
		do shell script "defaults write com.apple.finder DisableAllAnimations -bool false" with administrator privileges
		do shell script "defaults write com.apple.finder AnimateWindowZoom -bool true" with administrator privileges
		do shell script "defaults write com.apple.finder FXDisableFancyWindowTransition -bool false" with administrator privileges
	on error
		set stdout to stdout & "    unable to enable animations back" & newline
	end try

	set stdout to stdout & "  hide system files in Finder again ..." & newline
	try
		do shell script "defaults write com.apple.finder AppleShowAllFiles -bool false" with administrator privileges
	on error
		set stdout to stdout & "    hide system files in Finder back" & newline
	end try

	set stdout to stdout & "  relaunch Finder ..." & newline
	try
		tell application "Finder" to launch
	on error
		set stdout to stdout & "    failed to relaunch Finder" & newline
	end try

	-- at this point Finder should start cleanly and with no signs of TotalFinder
	-- you may check Events/Replies tab to see if there were no issues with uninstallation

	stdout -- this is needed for platypus to display output in details window
end run


INTEGRATION: CWS changefileheader (1.4.160); FILE MERGED 2008/03/31 16:04:19 rt 1.4.160.1: #i87441# Change license header to LPGL v3.

(*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: main.applescript,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 *************************************************************************)

(*==== (global variables as get-functions) ====*)

on getOOInstallPath()
	return (((path to me) as string) & "Contents:")
end getOOInstallPath

on getOOResourcesPath()
	return (((path to me) as string) & "Contents:Resources:")
end getOOResourcesPath

on getOOProgramPath()
	return (getOOInstallPath() & "MacOS:")
end getOOProgramPath

on getScriptPath()
	-- set this to absolute path when debugging
	return (((path to me) as string) & "Contents:Resources:Scripts:")
end getScriptPath

on getOOUserSettingsPath()
	return (((path to home folder) as string) & "Library:Application Support:OpenOffice.org:%USERDIRPRODUCTVERSION:")
end getOOUserSettingsPath

on getOOUserFontPath()
	return (getOOUserSettingsPath() & "user:fonts:")
end getOOUserFontPath

on getUserLogsPath()
	return (((path to home folder) as string) & "Library:Logs:")
end getUserLogsPath

on shellTerminator()
	return (" &>/dev/null & echo $!") as string
end shellTerminator

--
-- the default handlers: run, open, idle, quit
--

on run
	if (preRun()) then
		logEvent("(Scripts/main) Running OpenOffice.org")
		openSoffice("-")
	end if
end run

on open (theFiles)
	if (preRun()) then
		openFiles(theFiles)
	end if
end open

on idle
	-- close icon only if ooo has terminated
	if (hasOOoQuit()) then
		tell me to quit
	end if
	-- check all x seconds if ok to quit
	return 3
end idle

on quit
	if (hasOOoQuit()) then
		continue quit
	end if
end quit

-------------------------------------------------------------

on preRun()

	-- Check for the required version of Mac OS X
	if (not atLeastOSXVersion(10, 3, 0)) then
		display dialog getMessage("ERROR_NEED_PANTHER")
		return false
	end if

	-- Check for that OOo can be found
	if (not isRealPath(getOOProgramPath())) then
		display dialog getMessage("ERROR_OOO_NOT_FOUND")
		return false
	end if

	if (not isRealPath(getOOUserFontPath())) then
		set createUserFont to "mkdir -p " & (quoted form of POSIX path of getOOUserFontPath()) & "; "
		do shell script createUserFont
	end if

	-- If no crash occured before, ~/Library/Logs does not exist, and OpenOffice.org cannot be started
	if (not isRealPath(getUserLogsPath())) then
		set createUserLogsPath to "mkdir -p " & (quoted form of POSIX path of getUserLogsPath()) & "; "
		do shell script createUserLogsPath
	end if

	-- Checks are ok, now do the PostInstall stuff (e.g. fondu)

	-- load helper library
	set postinstall to load script alias
		(getScriptPath() & "PostInstall.scpt")
	-- execute the postinstall script
	run of postinstall

	return true
end preRun

on hasOOoQuit()
	if (isRealPath(getOOProgramPath())) then
		-- set the location of soffice binary
		set soffice to (quoted form of (POSIX path of getOOProgramPath() & "soffice"))

		set isRunning to do shell script "_FOUND_=`ps -wx -o command | grep " & soffice & " | grep -v grep`; echo $_FOUND_"
		if isRunning  "" then
			return false
		else
			return true
		end if
	else
		return true
	end if
end hasOOoQuit

on openSoffice(aFile)
	set theDisplay to startXServer()
	if (theDisplay is equal to "error") then
		return
	end if
	set theEnv to "DISPLAY=" & theDisplay & " ; export DISPLAY; "
	set theCmd to "sh " & (quoted form of (POSIX path of getOOProgramPath() & "soffice")) & " "
	do shell script theEnv & theCmd & aFile & shellTerminator()
	-- logEvent("open CMD: " & theEnv & theCmd & aFile)
end openSoffice

-- helper function to start X11 server
on startXServer()

	-- get X settings
	set XSettingsList to findXServer()
	set whichserver to item 1 of XSettingsList
	set Xserverloc to item 2 of XSettingsList

	-- debug:
	-- logEvent("(scripts/main) X settings: " & whichserver & "--" & POSIX path of Xserverloc)
	-- set whichserver to "NOXSERVER"

	-- if nothing really was found, display an error message.
	if (whichserver is equal to "NOXSERVER") then

		display dialog getMessage("ERROR_NEED_X11") buttons {"Quit", "More Info"} default button "More Info"
		if the button returned of the result is "Quit" then
			quit
		else
			-- if more info is chosen, then open a help web page
			do shell script "open http://porting.openoffice.org/mac/faq/installing/X11.html"
			-- cannot continue, so quit the script
			return "error"
		end if

	end if

	set now_running to ""
	set now_running to do shell script "INX=`ps -wcx | grep  " & quoted form of (whichserver & "$") & "`; echo $INX"
	if whichserver = "NOXSERVER" then
		-- display dialog "No XServer Found"
		set now_running to "Skip"
	end if
	if now_running = "" then
		if whichserver = "X11" then
			set x11cmd to quoted form of (Xserverloc & "/Contents/MacOS/X11") & shellTerminator()
			do shell script x11cmd
			-- save process id
			set x11pid to the result
			-- wait until the window manager is started which is the second child process of x11
			set numchildrencmd to "ps -x -o ppid | grep " & x11pid & " | wc -l"
			set numchildren to 0
			set d to current date
			set t1 to time of d
			repeat while numchildren  2
				set d to current date
				set t2 to time of d
				-- give up after 30 seconds
				if t2 - t1 > 30 then
					display dialog "Command timed out"
					exit repeat
				end if
				set result to do shell script numchildrencmd
				set numchildren to result as integer
			end repeat
		else -- startup XDarwin
			do shell script "open " & quoted form of Xserverloc & shellTerminator()
			do shell script "sleep 4"
		end if
	end if
	if whichserver is equal to "X11" then
		-- the DISPLAY variable is different for every user currently logged in
		-- X11 passes the DISPLAY as the last command line parameter to its child process
		-- we can use ps to read the command line and parse the trailing :0, :1, or whatever
		set xdisplay to do shell script "ps -wx -o command | grep X11.app | grep \":.$\" | sed \"s/^.*:/:/g\""
		--display dialog xdisplay
		return xdisplay
	else
		-- TODO: find out how XDarwin does it
		return ":0"
	end if
end startXServer

on openFiles(fileList)
	if (count of fileList) > 0 then
		repeat with i from 1 to the count of fileList
			set theDocument to (item i of fileList)
			set theFilePath to (quoted form of POSIX path of theDocument)
			set theFileInfo to (info for theDocument)
			openSoffice(theFilePath)
			logEvent("(Scripts/main) Open file: " & theFilePath)
		end repeat
	end if
end openFiles

(* ===== (Helper functions) ======= *)

-- get a localized string
on getMessage(aKey)
	try
		if (aKey is equal to "YES_KEY") then
			return "Yes"
		end if

		if (aKey is equal to "NO_KEY") then
			return "No"
		end if

		if (aKey is equal to "ERROR_OOO_NOT_FOUND") then
			return "OpenOffice.org was not found on your system. Please (re-)install OpenOffice.org first."
		end if

		if (aKey is equal to "ERROR_NEED_PANTHER") then
			return "This build of OpenOffice.org cannot be run on this system, OpenOffice.org requires MacOSX 10.3 (Panther) or newer system"
		end if

		if (aKey is equal to "ERROR_NEED_X11") then
			return "OpenOffice.org for Mac OS X cannot be started, because the X11 software is not installed. Please install Apple X11 first from the Mac OS X install DVD. More information: http://porting.openoffice.org/mac/faq/installing/X11.html"
		end if
	end try
end getMessage

-- function for logging script messages
on logEvent(themessage)
	set theLine to (do shell script
		"date  +'%Y-%m-%d %H:%M:%S'" as string)
		& " " & themessage
	do shell script "echo " & quoted form of theLine &
		" >> ~/Library/Logs/OpenOffice%USERDIRPRODUCTVERSION.log"
end logEvent

-- function for checking if a path exists
on isRealPath(aPath)
	try
		alias aPath
		return true
	on error
		-- error number -43 from aPath
		-- display dialog "NotRP -- " & aPath
		return false
	end try
end isRealPath

-- try to find X11 server on the Mac OS X system
-- return value: the found server or "NOXSERVER"
on findXServer()
	-- First try standard X11 location, then try standard XDarwin location

	set whichserver to "NOXSERVER"
	--Utilities folder of system
	set Xserverloc to ((path to utilities folder from system domain) as string) & "X11.app:"
	--display dialog " Xserverloc" & Xserverloc
	if (isRealPath(Xserverloc)) then
		set whichserver to "X11"
		set Xserverloc to (POSIX path of Xserverloc)
	else
		--Applications folder of system
		set Xserverloc to ((path to applications folder from system domain) as string) & "XDarwin.app:"
		if (isRealPath(Xserverloc)) then
			set whichserver to "XDarwin"
			set Xserverloc to (POSIX path of Xserverloc)
		end if
	end if

	-- if nothing found yet try using locate, first with X11.app and then with XDarwin.app
	if (whichserver is equal to "NOXSERVER") then
		set Xserverloc to do shell script "locate X11.app/Contents/MacOS/X11 | sed -e 's-/Contents/MacOS/X11--g'"
		if Xserverloc  "" then
			set whichserver to "X11"
		end if
	end if

	if (whichserver is equal to "NOXSERVER") then
		set Xserverloc to do shell script "locate XDarwin.app/Contents/MacOS/XDarwin | sed -e 's-/Contents/MacOS/XDarwin--g'"
		if Xserverloc  "" then
			set whichserver to "XDarwin"
		end if
	end if

	return {whichserver, Xserverloc}
end findXServer

-- Test for a minimum version of Mac OS X
on atLeastOSXVersion(verMajor, verMinor, verStep)
	-- The StandardAdditions's 'system attribute' used to be the Finder's 'computer' command.
	tell application "Finder" to set sysv to (system attribute "sysv")

	-- Generate sysv-compatible number from given version
	set reqVer to ((verMajor div 10) * 4096 + (verMajor mod 10) * 256 + verMinor * 16 + verStep)

	-- DEBUGGING:
	-- display dialog ("RV:" & reqVer & " < " & sysv as string)

	-- set major to ((sysv div 4096) * 10 + (sysv mod 4096 div 256))
	-- set minor to (sysv mod 256 div 16)
	-- set step to (sysv mod 16)
	-- display dialog ("Your Mac OS X version: " & major & "." & minor & "." & step)

	if (reqVer > sysv) then
		return false
	else
		return true
	end if
end atLeastOSXVersion

(*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: main.applescript,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 11:52:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 *************************************************************************)

(*==== (global variables as get-functions) ====*)

on getOOInstallPath()
	return (((path to me) as string) & "Contents:")
end getOOInstallPath

on getOOResourcesPath()
	return (((path to me) as string) & "Contents:Resources:")
end getOOResourcesPath

on getOOProgramPath()
	return (getOOInstallPath() & "MacOS:")
end getOOProgramPath

on getScriptPath()
	-- set this to absolute path when debugging
	return (((path to me) as string) & "Contents:Resources:Scripts:")
end getScriptPath

on getOOUserSettingsPath()
	return (((path to home folder) as string) & "Library:Application Support:OpenOffice.org:%USERDIRPRODUCTVERSION:")
end getOOUserSettingsPath

on getOOUserFontPath()
	return (getOOUserSettingsPath() & "user:fonts:")
end getOOUserFontPath

on getUserLogsPath()
	return (((path to home folder) as string) & "Library:Logs:")
end getUserLogsPath

on shellTerminator()
	return (" &>/dev/null & echo $!") as string
end shellTerminator

--
-- the default handlers: run, open, idle, quit
--

on run
	if (preRun()) then
		logEvent("(Scripts/main) Running OpenOffice.org")
		openSoffice("-")
	end if
end run

on open (theFiles)
	if (preRun()) then
		openFiles(theFiles)
	end if
end open

on idle
	-- close icon only if ooo has terminated
	if (hasOOoQuit()) then
		tell me to quit
	end if
	-- check all x seconds if ok to quit
	return 3
end idle

on quit
	if (hasOOoQuit()) then
		continue quit
	end if
end quit

-------------------------------------------------------------

on preRun()

	-- Check for the required version of Mac OS X
	if (not atLeastOSXVersion(10, 3, 0)) then
		display dialog getMessage("ERROR_NEED_PANTHER")
		return false
	end if

	-- Check for that OOo can be found
	if (not isRealPath(getOOProgramPath())) then
		display dialog getMessage("ERROR_OOO_NOT_FOUND")
		return false
	end if

	if (not isRealPath(getOOUserFontPath())) then
		set createUserFont to "mkdir -p " & (quoted form of POSIX path of getOOUserFontPath()) & "; "
		do shell script createUserFont
	end if

	-- If no crash occured before, ~/Library/Logs does not exist, and OpenOffice.org cannot be started
	if (not isRealPath(getUserLogsPath())) then
		set createUserLogsPath to "mkdir -p " & (quoted form of POSIX path of getUserLogsPath()) & "; "
		do shell script createUserLogsPath
	end if

	-- Checks are ok, now do the PostInstall stuff (e.g. fondu)

	-- load helper library
	set postinstall to load script alias
		(getScriptPath() & "PostInstall.scpt")
	-- execute the postinstall script
	run of postinstall

	return true
end preRun

on hasOOoQuit()
	if (isRealPath(getOOProgramPath())) then
		-- set the location of soffice binary
		set soffice to (quoted form of (POSIX path of getOOProgramPath() & "soffice"))

		set isRunning to do shell script "_FOUND_=`ps -wx -o command | grep " & soffice & " | grep -v grep`; echo $_FOUND_"
		if isRunning  "" then
			return false
		else
			return true
		end if
	else
		return true
	end if
end hasOOoQuit

on openSoffice(aFile)
	set theDisplay to startXServer()
	if (theDisplay is equal to "error") then
		return
	end if
	set theEnv to "DISPLAY=" & theDisplay & " ; export DISPLAY; "
	set theCmd to "sh " & (quoted form of (POSIX path of getOOProgramPath() & "soffice")) & " "
	do shell script theEnv & theCmd & aFile & shellTerminator()
	-- logEvent("open CMD: " & theEnv & theCmd & aFile)
end openSoffice

-- helper function to start X11 server
on startXServer()

	-- get X settings
	set XSettingsList to findXServer()
	set whichserver to item 1 of XSettingsList
	set Xserverloc to item 2 of XSettingsList

	-- debug:
	-- logEvent("(scripts/main) X settings: " & whichserver & "--" & POSIX path of Xserverloc)
	-- set whichserver to "NOXSERVER"

	-- if nothing really was found, display an error message.
	if (whichserver is equal to "NOXSERVER") then

		display dialog getMessage("ERROR_NEED_X11") buttons {"Quit", "More Info"} default button "More Info"
		if the button returned of the result is "Quit" then
			quit
		else
			-- if more info is chosen, then open a help web page
			do shell script "open http://porting.openoffice.org/mac/faq/installing/X11.html"
			-- cannot continue, so quit the script
			return "error"
		end if

	end if

	set now_running to ""
	set now_running to do shell script "INX=`ps -wcx | grep  " & quoted form of (whichserver & "$") & "`; echo $INX"
	if whichserver = "NOXSERVER" then
		-- display dialog "No XServer Found"
		set now_running to "Skip"
	end if
	if now_running = "" then
		if whichserver = "X11" then
			set x11cmd to quoted form of (Xserverloc & "/Contents/MacOS/X11") & shellTerminator()
			do shell script x11cmd
			-- save process id
			set x11pid to the result
			-- wait until the window manager is started which is the second child process of x11
			set numchildrencmd to "ps -x -o ppid | grep " & x11pid & " | wc -l"
			set numchildren to 0
			set d to current date
			set t1 to time of d
			repeat while numchildren  2
				set d to current date
				set t2 to time of d
				-- give up after 30 seconds
				if t2 - t1 > 30 then
					display dialog "Command timed out"
					exit repeat
				end if
				set result to do shell script numchildrencmd
				set numchildren to result as integer
			end repeat
		else -- startup XDarwin
			do shell script "open " & quoted form of Xserverloc & shellTerminator()
			do shell script "sleep 4"
		end if
	end if
	if whichserver is equal to "X11" then
		-- the DISPLAY variable is different for every user currently logged in
		-- X11 passes the DISPLAY as the last command line parameter to its child process
		-- we can use ps to read the command line and parse the trailing :0, :1, or whatever
		set xdisplay to do shell script "ps -wx -o command | grep X11.app | grep \":.$\" | sed \"s/^.*:/:/g\""
		--display dialog xdisplay
		return xdisplay
	else
		-- TODO: find out how XDarwin does it
		return ":0"
	end if
end startXServer

on openFiles(fileList)
	if (count of fileList) > 0 then
		repeat with i from 1 to the count of fileList
			set theDocument to (item i of fileList)
			set theFilePath to (quoted form of POSIX path of theDocument)
			set theFileInfo to (info for theDocument)
			openSoffice(theFilePath)
			logEvent("(Scripts/main) Open file: " & theFilePath)
		end repeat
	end if
end openFiles

(* ===== (Helper functions) ======= *)

-- get a localized string
on getMessage(aKey)
	try
		if (aKey is equal to "YES_KEY") then
			return "Yes"
		end if

		if (aKey is equal to "NO_KEY") then
			return "No"
		end if

		if (aKey is equal to "ERROR_OOO_NOT_FOUND") then
			return "OpenOffice.org was not found on your system. Please (re-)install OpenOffice.org first."
		end if

		if (aKey is equal to "ERROR_NEED_PANTHER") then
			return "This build of OpenOffice.org cannot be run on this system, OpenOffice.org requires MacOSX 10.3 (Panther) or newer system"
		end if

		if (aKey is equal to "ERROR_NEED_X11") then
			return "OpenOffice.org for Mac OS X cannot be started, because the X11 software is not installed. Please install Apple X11 first from the Mac OS X install DVD. More information: http://porting.openoffice.org/mac/faq/installing/X11.html"
		end if
	end try
end getMessage

-- function for logging script messages
on logEvent(themessage)
	set theLine to (do shell script
		"date  +'%Y-%m-%d %H:%M:%S'" as string)
		& " " & themessage
	do shell script "echo " & quoted form of theLine &
		" >> ~/Library/Logs/OpenOffice%USERDIRPRODUCTVERSION.log"
end logEvent

-- function for checking if a path exists
on isRealPath(aPath)
	try
		alias aPath
		return true
	on error
		-- error number -43 from aPath
		-- display dialog "NotRP -- " & aPath
		return false
	end try
end isRealPath

-- try to find X11 server on the Mac OS X system
-- return value: the found server or "NOXSERVER"
on findXServer()
	-- First try standard X11 location, then try standard XDarwin location

	set whichserver to "NOXSERVER"
	--Utilities folder of system
	set Xserverloc to ((path to utilities folder from system domain) as string) & "X11.app:"
	--display dialog " Xserverloc" & Xserverloc
	if (isRealPath(Xserverloc)) then
		set whichserver to "X11"
		set Xserverloc to (POSIX path of Xserverloc)
	else
		--Applications folder of system
		set Xserverloc to ((path to applications folder from system domain) as string) & "XDarwin.app:"
		if (isRealPath(Xserverloc)) then
			set whichserver to "XDarwin"
			set Xserverloc to (POSIX path of Xserverloc)
		end if
	end if

	-- if nothing found yet try using locate, first with X11.app and then with XDarwin.app
	if (whichserver is equal to "NOXSERVER") then
		set Xserverloc to do shell script "locate X11.app/Contents/MacOS/X11 | sed -e 's-/Contents/MacOS/X11--g'"
		if Xserverloc  "" then
			set whichserver to "X11"
		end if
	end if

	if (whichserver is equal to "NOXSERVER") then
		set Xserverloc to do shell script "locate XDarwin.app/Contents/MacOS/XDarwin | sed -e 's-/Contents/MacOS/XDarwin--g'"
		if Xserverloc  "" then
			set whichserver to "XDarwin"
		end if
	end if

	return {whichserver, Xserverloc}
end findXServer

-- Test for a minimum version of Mac OS X
on atLeastOSXVersion(verMajor, verMinor, verStep)
	-- The StandardAdditions's 'system attribute' used to be the Finder's 'computer' command.
	tell application "Finder" to set sysv to (system attribute "sysv")

	-- Generate sysv-compatible number from given version
	set reqVer to ((verMajor div 10) * 4096 + (verMajor mod 10) * 256 + verMinor * 16 + verStep)

	-- DEBUGGING:
	-- display dialog ("RV:" & reqVer & " < " & sysv as string)

	-- set major to ((sysv div 4096) * 10 + (sysv mod 4096 div 256))
	-- set minor to (sysv mod 256 div 16)
	-- set step to (sysv mod 16)
	-- display dialog ("Your Mac OS X version: " & major & "." & minor & "." & step)

	if (reqVer > sysv) then
		return false
	else
		return true
	end if
end atLeastOSXVersion


Change comments to be proper AppleScript style

-- Go AppleScript library

property package : "Go"
property packageRoot : missing value

-- Get working directory for a given document
on getWorkingDirectory(doc)
	tell application "Finder"
		return POSIX path of ((container of ((file of doc) as alias) as string))
	end tell
end getWorkingDirectory

-- Find Go.bbpackage root
-- Assumption: this is *always* run from within the package!
on getPackageRoot()
	tell application "Finder"
		set cwd to ((container of (path to me)) as alias)
		repeat until name of cwd is "Go.bbpackage"
			set cwd to (container of cwd as alias)
		end repeat
	end tell
	return POSIX path of (cwd as string)
end getPackageRoot

on exec(doc, cmd)
	tell application "BBEdit"
		if source language of doc is not "Go" then
			error "Not a Go source file"
		end if
	end tell

	if packageRoot is missing value then
		set packageRoot to getPackageRoot()
	end if

	set runner to quoted form of (POSIX path of (packageRoot as string) & "Contents/Resources/gorunner")
	set shellCmd to runner & space & "-d " & POSIX path of ((file of doc) as alias) & space & cmd
	return do shell script (shellCmd)
end exec

on execCommands(doc, commands)
	set output to {}
	repeat with cmd in commands
		set entry to exec(doc, cmd)
		if length of entry > 0 then
			copy entry to the end of output
		end if
	end repeat
	return output
end execCommands

on packagePath(doc)
	return quoted form of exec(doc, "go list")
end packagePath

-- Parse message into result browser entry
--
-- Format:
--     [/path/to/file]:[line]:(col): [message]
on makeEntry(itemData, cwd)
	try
		-- Get source path
		set src to text 1 thru ((offset of ":" in itemData) - 1) of itemData
		if src starts with "./" then
			set srcFile to POSIX file (cwd & text 3 thru -1 of src)
		else
			set srcFile to POSIX file (src)
		end if

		-- Get line:column
		set lineColumn to text ((offset of ":" in itemData) + 1) thru ((offset of ": " in itemData) - 1) of itemData
		set lineNumber to (text 1 thru ((offset of ":" in lineColumn) - 1) of lineColumn) as number
		set columnNumber to (text ((offset of ":" in lineColumn) + 1) thru -1 of lineColumn) as number

		-- Get message
		set msg to text ((offset of ": " in itemData) + 2) thru -1 of itemData

		tell application "BBEdit"
			set resultKind to error_kind
			--	if resultType is "note" then
			--		set resultKind to note_kind
			--	else if resultType is "warning" then
			--		set resultKind to warning_kind
			--	else
			--		set resultKind to error_kind
			--	end if

			set entry to {result_kind:resultKind, result_file:srcFile, result_line:lineNumber, message:msg}
		end tell
		return entry
	on error msg
		log "Error: " & msg
		return missing value
	end try
end makeEntry

-- Filter and sort incoming messages
on prepareMessages(messages)
	set prevDelimiter to AppleScript's text item delimiters
	set AppleScript's text item delimiters to {ASCII character 10}
	set filteredString to do shell script ("echo " & quoted form of (messages as string) & " | sort -f | uniq")
	set AppleScript's text item delimiters to prevDelimiter
	return paragraphs of filteredString
end prepareMessages

on showResults(title, doc, messages)
	tell application "Finder"
		set cwd to POSIX path of ((container of (doc as alias) as string))
	end tell

	set errorList to {}
	set messageList to prepareMessages(messages)

	repeat with msg in messageList
		if msg does not start with "#" then
			set entry to makeEntry(msg, cwd)
			if entry is not missing value then
				copy entry to the end of errorList
			end if
		end if
	end repeat

	if (count of errorList) > 0 then
		try
			tell application "BBEdit"
				make new results browser with data errorList with properties {name:title}
			end tell
		on error msg
			log "Error: " & msg
		end try
	end if
end showResults

on handleDocumentDidSave(doc)
	try
		set docPath to POSIX path of ((file of doc) as string)
		set pkgPath to packagePath(doc)
		set goCommands to {"goimports -w " & quoted form of docPath, "golint " & quoted form of docPath, "go build", "go test"}
		set output to execCommands(doc, goCommands)
		if output is not missing value then
			showResults("Save " & (name of doc), POSIX file (docPath), output)
		end if
	on error msg
		log "Error handleDocumentDidSave: " & msg
	end try
end handleDocumentDidSave

(*
on run
	tell application "BBEdit" to set doc to active document of window 1
	handleDocumentDidSave(doc)
end run
*)

-- Go AppleScript library

property package : "Go"
property packageRoot : missing value

-- Get working directory for a given document
on getWorkingDirectory(doc)
	tell application "Finder"
		return POSIX path of ((container of ((file of doc) as alias) as string))
	end tell
end getWorkingDirectory

-- Find Go.bbpackage root
-- Assumption: this is *always* run from within the package!
on getPackageRoot()
	tell application "Finder"
		set cwd to ((container of (path to me)) as alias)
		repeat until name of cwd is "Go.bbpackage"
			set cwd to (container of cwd as alias)
		end repeat
	end tell
	return POSIX path of (cwd as string)
end getPackageRoot

on exec(doc, cmd)
	tell application "BBEdit"
		if source language of doc is not "Go" then
			error "Not a Go source file"
		end if
	end tell

	if packageRoot is missing value then
		set packageRoot to getPackageRoot()
	end if

	set runner to quoted form of (POSIX path of (packageRoot as string) & "Contents/Resources/gorunner")
	set shellCmd to runner & space & "-d " & POSIX path of ((file of doc) as alias) & space & cmd
	return do shell script (shellCmd)
end exec

on execCommands(doc, commands)
	set output to {}
	repeat with cmd in commands
		set entry to exec(doc, cmd)
		if length of entry > 0 then
			copy entry to the end of output
		end if
	end repeat
	return output
end execCommands

on packagePath(doc)
	return quoted form of exec(doc, "go list")
end packagePath

# Parse message into result browser entry
#
# Format:
#     [/path/to/file]:[line]:(col): [message]
on makeEntry(itemData, cwd)
	try
		# Get source path
		set src to text 1 thru ((offset of ":" in itemData) - 1) of itemData
		if src starts with "./" then
			set srcFile to POSIX file (cwd & text 3 thru -1 of src)
		else
			set srcFile to POSIX file (src)
		end if

		# Get line:column
		set lineColumn to text ((offset of ":" in itemData) + 1) thru ((offset of ": " in itemData) - 1) of itemData
		set lineNumber to (text 1 thru ((offset of ":" in lineColumn) - 1) of lineColumn) as number
		set columnNumber to (text ((offset of ":" in lineColumn) + 1) thru -1 of lineColumn) as number

		# Get message
		set msg to text ((offset of ": " in itemData) + 2) thru -1 of itemData

		tell application "BBEdit"
			set resultKind to error_kind
			#	if resultType is "note" then
			#		set resultKind to note_kind
			#	else if resultType is "warning" then
			#		set resultKind to warning_kind
			#	else
			#		set resultKind to error_kind
			#	end if

			set entry to {result_kind:resultKind, result_file:srcFile, result_line:lineNumber, message:msg}
		end tell
		return entry
	on error msg
		log "Error: " & msg
		return missing value
	end try
end makeEntry

-- Filter and sort incoming messages
on prepareMessages(messages)
	set prevDelimiter to AppleScript's text item delimiters
	set AppleScript's text item delimiters to {ASCII character 10}
	set filteredString to do shell script ("echo " & quoted form of (messages as string) & " | sort -f | uniq")
	set AppleScript's text item delimiters to prevDelimiter
	return paragraphs of filteredString
end prepareMessages

on showResults(title, doc, messages)
	tell application "Finder"
		set cwd to POSIX path of ((container of (doc as alias) as string))
	end tell

	set errorList to {}
	set messageList to prepareMessages(messages)

	repeat with msg in messageList
		if msg does not start with "#" then
			set entry to makeEntry(msg, cwd)
			if entry is not missing value then
				copy entry to the end of errorList
			end if
		end if
	end repeat

	if (count of errorList) > 0 then
		try
			tell application "BBEdit"
				make new results browser with data errorList with properties {name:title}
			end tell
		on error msg
			log "Error: " & msg
		end try
	end if
end showResults

on handleDocumentDidSave(doc)
	try
		set docPath to POSIX path of ((file of doc) as string)
		set pkgPath to packagePath(doc)
		set goCommands to {"goimports -w " & quoted form of docPath, "golint " & quoted form of docPath, "go build", "go test"}
		set output to execCommands(doc, goCommands)
		if output is not missing value then
			showResults("Save " & (name of doc), POSIX file (docPath), output)
		end if
	on error msg
		log "Error handleDocumentDidSave: " & msg
	end try
end handleDocumentDidSave

(*
on run
	tell application "BBEdit" to set doc to active document of window 1
	handleDocumentDidSave(doc)
end run
*)