-
Notifications
You must be signed in to change notification settings - Fork 0
/
PlugNPlayMac.sh
executable file
·309 lines (239 loc) · 12.1 KB
/
PlugNPlayMac.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#!/bin/bash
# bash -c "nohup caffeinate -u -i -d &"
# ps aux -o ppid | grep caffeinate
# launchctl load /Library/LaunchAgents/com.launch.plug.and.play.mac.plist
# launchctl unload /Library/LaunchAgents/com.launch.plug.and.play.mac.plist
# https://fig.io
# https://ohmyz.sh
# https://stackoverflow.com/questions/27379507/creating-and-writing-into-plist-with-terminal-or-bash-script
source /usr/local/bin/PlugNPlayMac/PNPMacParam.sh
# Password for usce bclm
myPassword=$(getPW)
# CPU Architecture (Intel: x86_64 --- Apple Silicon: arm64)
isAppleSilicon=$(detect_cpu_architecture)
log_error "" "$isAppleSilicon" "Start the PlugNPlayMac script"
while true; do
# Mode
isDisplayFound=false
isWifiFound=false
isSleep=false
CurrentOS=$(sw_vers -productVersion)
OS_VERSION=$(echo "$CurrentOS" | awk -F. '{print $1 "." $2}')
if (( $(echo "$OS_VERSION >= 15.0" | bc -l) )); then
currentWifi=$(system_profiler SPAirPortDataType | awk '/Current Network/ {getline;$1=$1;print $0 | "tr -d ':'";exit}')
# echo "$currentWifi"
else
commandDetectWifi="/Sy*/L*/Priv*/Apple8*/V*/C*/R*/airport -I | awk '/ SSID:/ {print $2}'"
# Return the name of the wifi connected to the mac
currentWifi=$(eval "$commandDetectWifi")
# If currentWifi is empty, try another method
if [ -z "$currentWifi" ]; then
log_error "E0" "$isAppleSilicon" "Can't find the wifi with airport -I"
for i in {0..100}; do
# Get the Wi-Fi network name
currentWifi=$(networksetup -getairportnetwork en$i | awk -F ': ' '/Current Wi-Fi Network/{print $2}')
# If currentWifi is not empty, break the loop
if [ ! -z "$currentWifi" ]; then
log_error "E0" "$isAppleSilicon" "Wi-Fi found with at en$i"
break
fi
done
if [ -z "$currentWifi" ]; then
log_error "E0" "$isAppleSilicon" "Can't find the wifi with networksetup"
fi
currentWifi=$(echo "$currentWifi" | sed 's/Current Wi-Fi Network: //')
fi
fi
# echo "$currentWifi"
if $isAppleSilicon; then
# Get the complete output of system_profiler SPDisplaysDataType
display_info=$(system_profiler SPDisplaysDataType)
# Extract display names
display_names_and_resolutions=$(echo "$display_info" | awk '/Displays:/{p=1; next} p && /^$/{p=0} p && !/^$/ && $1 != "Display" {if ($1 == "Display") name=$2; else if ($1 == "Resolution:") print name, prev_line} {prev_line = $0}')
# Use sed to remove trailing colons from names, "Display Type:" and leading spaces in lines
currentDisplay=$(echo "$display_names_and_resolutions" | sed -e 's/:$//' -e 's/Display Type: //' -e 's/^[[:space:]]*//')
# Print display names and their respective resolutions
# echo "$currentDisplay"
# Get the complete output of system_profiler SPDisplaysDataType
display_info=$(system_profiler SPDisplaysDataType)
# Count the occurrences of "Display Asleep: Yes" and "Display Asleep: No"
count_asleep=$(echo "$display_info" | grep -c "Display Asleep: Yes")
count_awake=$(echo "$display_info" | grep -c "Display Asleep: No")
else
# Return the name of the different display connected to the mac
# If the built in display is connected but close it doesn't appear
commandDetectDisplay="ioreg -lw0 | grep 'IODisplayEDID' | sed '/[^<]*</s///' | xxd -p -r | strings -10"
currentDisplay=$(eval "$commandDetectDisplay")
# echo "$currentDisplay"
commandSleepStatus='echo $(ioreg -n IODisplayWrangler | grep -i IOPowerManagement | perl -pe '\''s/^.*DevicePowerState"=([0-9]+).*$/\1/'\'')/4 | bc'
sleepStatus=$(eval "$commandSleepStatus")
# echo "$sleepStatus"
fi
# Set isDisplayFound to true if there is a match on the display
for displayName in "${listDisplayNames[@]}"; do
if [[ "$currentDisplay" == *"$displayName"* ]]; then
isDisplayFound=true
break
fi
done
# Set isWifiFound to true if there is a match on the wifi
for wifiName in "${listWifiNames[@]}"; do
if [[ "$currentWifi" == *"$wifiName"* ]]; then
isWifiFound=true
break
fi
done
# Set isRunning to false if the sleep is active
if [[ "$sleepStatus" -eq 0 && "$isAppleSilicon" == false ]]; then
isSleep=true
elif [[ $count_asleep -gt 0 && $count_awake -eq 0 && "$isAppleSilicon" == true ]]; then
isSleep=true
fi
# Get the timestamp of the last user interaction from the idle time
idle_time_seconds=$(ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print int($NF/1000000000); exit}')
idle_time_minutes=$((idle_time_seconds / 60))
# date_string=$(date +"%b %d %Y - %H:%M")
# echo "$date_string: Last interaction was $idle_time_seconds seconds ago and $idle_time_minutes minutes ago"
if [[ $firstTime == false ]]; then
# Check if it's been more than 10 minutes since firstTime was set to false
currentTime=$(date +%s)
timeDifference=$((currentTime - lastUpdateTime))
if (( timeDifference > 300 )); then
firstTime=true
log_error "S1" "$isAppleSilicon" "More than 10 minutes have passed since the last check. Resetting firstTime to true"
fi
fi
if [[ $isDisplayFound == true && $isWifiFound == true ]]; then
if [[ $isRunning == false && $isSleep == false ]]; then
# If is passed less than 10 minutes from the last user interaction
# Needed for prevent the mac start caffeinate when the user is not using the mac
if [ "$idle_time_minutes" -lt 10 ]; then
pkill caffeinate
# Launch a nohup caffeinate for run caffeinate in background
# This prevent the mac to sleep
# "man caffeinate" for more information
(nohup caffeinate -u -i -d & wait 2>/dev/null) &
# save the caffeinate process ID
PMSETPID=$!
log_error "S1" "$isAppleSilicon" "Starting caffeinate with ID: $PMSETPID"
isRunning=true
isCaffeinate=true
fi
# Open each application in the list
for applicationName in "${listAppToOpen[@]}"; do
if ! open -a "$applicationName" 2>&1 | grep -q "Unable to find application named '$applicationName'"; then
log_error "S2" "$isAppleSilicon" "Starting the APP: $applicationName"
else
notFoundedApp+=("$applicationName")
log_error "E2" "$isAppleSilicon" "Unable to find the APP: $applicationName"
fi
done
areAppsOpen=true
batteryResult=0
if [ $isBclm == false ]; then
# More info on BCLM here: https://github.com/zackelia/bclm
# Overwrite battery value and set the new value for the battery limit
chmod +x "$parentPath/bclm"
if $isAppleSilicon; then
#FOR APPLE SILICON THE VALUE MUST BE 80 or 100
batteryValue=80
fi
# Prompt for the password and provide it to sudo without displaying it
writtenResult=$(echo "$myPassword" | sudo -S "$parentPath/bclm" write "$batteryValue" 2>&1)
if [ $? -eq 0 ]; then
log_error "S4" "$isAppleSilicon" "Value $batteryValue written successfully"
fi
# Apply the persistence for the new battery limit
error_message=$(echo "$myPassword" | sudo -S "$parentPath/bclm" persist 2>&1)
if [ $? -eq 0 ]; then
log_error "S5" "$isAppleSilicon" "Persistence has bean activte"
fi
# Read the current battery value
batteryResult="$("$parentPath/bclm" read)"
log_error "S6" "$isAppleSilicon" "Result of bclm read: $batteryResult"
if [ "$batteryResult" = "$batteryValue" ]; then
isBclm=true
fi
fi
elif [[ $isRunning == true && $isSleep == true ]]; then
if [ $isCaffeinate == true ]; then
# Kill all the caffeinate process
pkill caffeinate
date_string=$(date +"%b %d %Y - %H:%M")
# Check if any instances were killed
if [ $? -eq 0 ]; then
log_error "S7" "$isAppleSilicon" "All caffeinate process killed successfully"
else
log_error "E7" "$isAppleSilicon" "No caffeinate process found to kill"
fi
isCaffeinate=false
fi
elif [[ $isRunning == true && $isSleep == false ]]; then
if [ $isCaffeinate == false ]; then
# If is passed less than 10 minutes from the last user interaction
# Needed for prevent the mac start caffeinate when the user is not using the mac
if [ "$idle_time_minutes" -lt 10 ]; then
pkill caffeinate
(nohup caffeinate -u -i -d & wait 2>/dev/null) &
# save the caffeinate process ID
PMSETPID=$!
log_error "S8" "$isAppleSilicon" "Starting caffeinate with ID: $PMSETPID"
isCaffeinate=true
fi
fi
fi
elif [ $isDisplayFound == false ]; then
if [ $isRunning == true ]; then
# Check 2 times instead of one vecause sometimes the mac
# doesn't detect the second monitor correctly
if [[ $firstTime == true ]]; then
log_error "S91" "$isAppleSilicon" "First time the display is not found. Restart the check."
firstTime=false
lastUpdateTime=$(date +%s)
sleep 15
continue
fi
# Kill all the caffeinate process
pkill caffeinate
# Check if any instances were killed
if [ $? -eq 0 ]; then
log_error "S9" "$isAppleSilicon" "All caffeinate process killed successfully"
else
log_error "E9" "$isAppleSilicon" "No caffeinate process found to kill"
fi
isRunning=false
isCaffeinate=false
# Close each application in the list
for applicationName in "${listAppToOpen[@]}"; do
if [[ "${notFoundedApp[*]}" == *"$applicationName"* ]]; then
notFoundedApp=("${notFoundedApp[@]/$applicationName}")
echo "$date_string: $applicationName (E1) not found"
log_error "E10" "$isAppleSilicon" "$applicationName not found"
else
(osascript -e "tell application \"$applicationName\" to quit" & wait) 2>/dev/null
log_error "S10" "$isAppleSilicon" "$applicationName closed correctly"
fi
done
areAppsOpen=false
batteryResult=0
if [ $isBclm == true ]; then
# Remove persistence on the battery for set the default value
error_message=$(echo $myPassword | sudo -S "$parentPath/bclm" unpersist 2>&1)
date_string=$(date +"%b %d %Y - %H:%M")
if [ $? -eq 0 ]; then
log_error "S12" "$isAppleSilicon" "Persistence has bean disabled"
fi
# Write the original value
writtenResult=$(echo $myPassword | sudo -S "$parentPath/bclm" write 100)
# Remove the plist file of BCLM for prevent problem with the default value
rmFile=$(echo $myPassword | sudo -S rm /Library/LaunchDaemons/com.zackelia.bclm.plist)
batteryResult="$("$parentPath/bclm" read)"
log_error "S13" "$isAppleSilicon" "Result of bclm read: $batteryResult"
if [ "$batteryResult" = "100" ]; then
isBclm=false
fi
fi
fi
fi
sleep $seconds4Delay
done