chiark / gitweb /
5f75bc31b12c7e7634786d706c605fbc78916c90
[elogind.git] / shell-completion / systemd-zsh-completion.zsh
1 #compdef systemctl loginctl journalctl hostnamectl localectl timedatectl systemd-coredumpctl udevadm systemd-analyze systemd-cat systemd-ask-password systemd-cgls systemd-cgtop systemd-delta systemd-detect-virt systemd-inhibit systemd-machine-id-setup systemd-notify systemd-nspawn systemd-tmpfiles systemd-tty-ask-password-agent
2
3 _ctls()
4 {
5     local curcontext="$curcontext" state lstate line
6     case "$service" in
7         systemctl)
8             # -s for aggregated options like -aP
9             _arguments -s \
10                 {-h,--help}'[Show help]' \
11                 '--version[Show package version]' \
12                 {-t,--type=}'[List only units of a particular type]:unit type:(automount device mount path service snapshot socket swap target timer)' \
13                 \*{-p,--property=}'[Show only properties by specific name]:unit property' \
14                 {-a,--all}'[Show all units/properties, including dead/empty ones]' \
15                 '--failed[Show only failed units]' \
16                 "--full[Don't ellipsize unit names on output]" \
17                 '--fail[When queueing a new job, fail if conflicting jobs are pending]' \
18                 '--ignore-dependencies[When queueing a new job, ignore all its dependencies]' \
19                 '--kill-who=[Who to send signal to]:killwho:(main control all)' \
20                 {-s,--signal=}'[Which signal to send]:signal:_signals' \
21                 {-H,--host=}'[Show information for remote host]:userathost:_hosts_or_user_at_host' \
22                 {-P,--privileged}'[Acquire privileges before execution]' \
23                 {-q,--quiet}'[Suppress output]' \
24                 '--no-block[Do not wait until operation finished]' \
25                 "--no-wall[Don't send wall message before halt/power-off/reboot]" \
26                 "--no-reload[When enabling/disabling unit files, don't reload daemon configuration]" \
27                 '--no-legend[Do not print a legend, i.e. the column headers and the footer with hints]' \
28                 '--no-pager[Do not pipe output into a pager]' \
29                 '--no-ask-password[Do not ask for system passwords]' \
30                 '--order[When generating graph for dot, show only order]' \
31                 '--require[When generating graph for dot, show only requirement]' \
32                 '--system[Connect to system manager]' \
33                 '--user[Connect to user service manager]' \
34                 '--global[Enable/disable unit files globally]' \
35                 {-f,--force}'[When enabling unit files, override existing symlinks. When shutting down, execute action immediately]' \
36                 '--root=[Enable unit files in the specified root directory]:directory:_directories' \
37                 '--runtime[Enable unit files only temporarily until next reboot]' \
38                 {-n,--lines=}'[Journal entries to show]:number of entries' \
39                 {-o,--output=}'[Change journal output mode]:modes:_outputmodes' \
40                 '*::systemctl command:_systemctl_command'
41         ;;
42         loginctl)
43             _arguments -s \
44                 {-h,--help}'[Show help]' \
45                 '--version[Show package version]' \
46                 \*{-p,--property=}'[Show only properties by this name]:unit property' \
47                 {-a,--all}'[Show all properties, including empty ones]' \
48                 '--kill-who=[Who to send signal to]:killwho:(main control all)' \
49                 {-s,--signal=}'[Which signal to send]:signal:_signals' \
50                 '--no-ask-password[Do not ask for system passwords]' \
51                 {-H,--host=}'[Show information for remote host]:userathost:_hosts_or_user_at_host' \
52                 {-P,--privileged}'[Acquire privileges before execution]' \
53                 '--no-pager[Do not pipe output into a pager]' \
54                 '*::loginctl command:_loginctl_command'
55         ;;
56
57         hostnamectl)
58             _arguments -s \
59                 {-h,--help}'[Show this help]' \
60                 '--version[Show package version]' \
61                 '--transient[Only set transient hostname]' \
62                 '--static[Only set static hostname]' \
63                 '--pretty[Only set pretty hostname]' \
64                 '--no-ask-password[Do not prompt for password]' \
65                 {-H,--host=}'[Operate on remote host]:userathost:_hosts_or_user_at_host' \
66                 '*::hostnamectl commands:_hostnamectl_command'
67         ;;
68         journalctl)
69             _arguments -s \
70                 '--since=[Start showing entries newer or of the specified date]:YYYY-MM-DD HH\:MM\:SS' \
71                 '--until=[Stop showing entries older or of the specified date]:YYYY-MM-DD HH\:MM\:SS' \
72                 {-c,--cursor=}'[Start showing entries from specified cursor]:cursors:_journal_fields __CURSORS' \
73                 {-b,--this-boot}'[Show data only from current boot]' \
74                 {-u,--unit=}'[Show data only from the specified unit]:units:_journal_fields _SYSTEMD_UNIT' \
75                 {-p,--priority=}'[Show only messages within the specified priority range]:priority:_journal_fields PRIORITY' \
76                 {-f,--follow}'[Follow journal]' \
77                 {-n,--lines=}'[Number of journal entries to show]:integer' \
78                 '--no-tail[Show all lines, even in follow mode]' \
79                 {-o,--output=}'[Change journal output mode]:output modes:_outputmodes' \
80                 {-a,--all}'[Show all fields, including long and unprintable]' \
81                 {-q,--quiet}"[Don't show privilege warning]" \
82                 '--no-pager[Do not pipe output into a pager]' \
83                 {-m,--merge}'[Show entries from all available journals]' \
84                 {-D,--directory=}'[Show journal files from directory]:directories:_directories' \
85                 '--interval=[Time interval for changing the FSS sealing key]:time interval' \
86                 '--verify-key=[Specify FSS verification key]:FSS key' \
87                 {-h,--help}'[Show this help]' \
88                 '--version[Show package version]' \
89                 '--new-id128[Generate a new 128 Bit ID]' \
90                 '--header[Show journal header information]' \
91                 '--disk-usage[Show total disk usage]' \
92                 {-F,--field=}'[List all values a certain field takes]:Fields:_list_fields' \
93                 '--setup-keys[Generate new FSS key pair]' \
94                 '--verify[Verify journal file consistency]' \
95                 '--list-catalog[List messages in catalog]' \
96                 '--update-catalog[Update binary catalog database]' \
97         ;;
98         localectl)
99             _arguments \
100                 {-h,--help}'[Show this help]' \
101                 '--version[Show package version]' \
102                 "--no-convert[Don't convert keyboard mappings]" \
103                 '--no-pager[Do not pipe output into a pager]' \
104                 '--no-ask-password[Do not prompt for password]' \
105                 {-H,--host=}'[Operate on remote host]:userathost:_hosts_or_user_at_host' \
106                 '*::localectl commands:_localectl_command'
107         ;;
108         systemd-coredumpctl)
109             _arguments \
110                 {-o,--output=}'[Write output to FILE]:output file:_files' \
111                 '--no-pager[Do not pipe output into a pager]' \
112                 {-h,--help}'[Show this help]' \
113                 '--version[Show package version]' \
114                 '*::systemd-coredumpctl commands:_systemd-coredumpctl_command'
115
116         ;;
117         timedatectl)
118             _arguments -s \
119                 {-h,--help}'[Show this help]' \
120                 '--version[Show package version]' \
121                 '--adjust-system-clock[Adjust system clock when changing local RTC mode]' \
122                 '--no-pager[Do not pipe output into a pager]' \
123                 '--no-ask-password[Do not prompt for password]' \
124                 {-H,--host=}'[Operate on remote host]:userathost:_hosts_or_user_at_host' \
125                 '*::timedatectl commands:_timedatectl_command'
126         ;;
127         udevadm)
128             _arguments \
129                 '--debug[Print debug messages to stderr]' \
130                 '--version[Print version number]' \
131                 '--help[Print help text]' \
132                 '*::udevadm commands:_udevadm_command'
133         ;;
134         systemd-analyze)
135             _arguments \
136                 {-h,--help}'[Show help text.]' \
137                 '--user[Shows performance data of user sessions instead of the system manager.]' \
138                 '*::systemd-analyze commands:_systemd_analyze_command'
139         ;;
140         systemd-ask-password)
141             _arguments \
142                 {-h,--help}'[Show this help]' \
143                 '--icon=[Icon name]' \
144                 '--timeout=[Timeout in sec]' \
145                 '--no-tty[Ask question via agent even on TTY]' \
146                 '--accept-cached[Accept cached passwords]' \
147                 '--multiple[List multiple passwords if available]'
148         ;;
149         systemd-cat)
150             _arguments \
151                 {-h,--help}'[Show this help]' \
152                 '--version[Show package version.]' \
153                 {-t,--identifier=}'[Set syslog identifier.]' \
154                 {-p,--priority=}'[Set priority value.]:value:({0..7})' \
155                 '--level-prefix=[Control whether level prefix shall be parsed.]:boolean:(1 0)' \
156                 ':Message'
157         ;;
158         systemd-cgls)
159             _arguments \
160                 {-h,--help}'[Show this help]' \
161                 '--version[Show package version]' \
162                 '--no-pager[Do not pipe output into a pager]' \
163                 {-a,--all}'[Show all groups, including empty]' \
164                 '-k[Include kernel threads in output]' \
165                 ':cgroups:(cpuset cpu cpuacct memory devices freezer net_cls blkio)'
166         ;;
167         systemd-cgtop)
168             _arguments \
169                 {-h,--help}'[Show this help]' \
170                 '--version[Print version and exit]' \
171                 '(-c -m -i -t)-p[Order by path]' \
172                 '(-c -p -m -i)-t[Order by number of tasks]' \
173                 '(-m -p -i -t)-c[Order by CPU load]' \
174                 '(-c -p -i -t)-m[Order by memory load]' \
175                 '(-c -m -p -t)-i[Order by IO load]' \
176                 {-d,--delay=}'[Specify delay]' \
177                 {-n,--iterations=}'[Run for N iterations before exiting]' \
178                 {-b,--batch}'[Run in batch mode, accepting no input]' \
179                 '--depth=[Maximum traversal depth]'
180         ;;
181         systemd-delta)
182             _arguments \
183                 {-h,--help}'[Show this help]' \
184                 '--version[Show package version]' \
185                 '--no-pager[Do not pipe output into a pager]' \
186                 '--diff=[Show a diff when overridden files differ]:boolean:(1 0)' \
187                 {-t,--type=}'[Only display a selected set of override types]:types:(masked equivalent redirected overridden unchanged)' \
188                 ':SUFFIX:(tmpfiles.d sysctl.d systemd/system)'
189         ;;
190         systemd-detect-virt)
191             _arguments \
192                 {-h,--help}'[Show this help]' \
193                 '--version[Show package version]' \
194                 {-c,--container}'[Only detect whether we are run in a container]' \
195                 {-v,--vm}'[Only detect whether we are run in a VM]' \
196                 {-q,--quiet}"[Don't output anything, just set return value]"
197         ;;
198         systemd-inhibit)
199             _arguments \
200                 {-h,--help}'[Show this help]' \
201                 '--version[Show package version]' \
202                 '--what=[Operations to inhibit]:options:(shutdown sleep idle handle-power-key handle-suspend-key handle-hibernate-key handle-lid-switch)' \
203                 '--who=[A descriptive string who is inhibiting]' \
204                 '--why=[A descriptive string why is being inhibited]' \
205                 '--mode=[One of block or delay]' \
206                 '--list[List active inhibitors]' \
207                 '*:commands:_systemd_inhibit_command'
208         ;;
209         systemd-machine-id-setup)
210             _arguments \
211                 {-h,--help}'[Show this help]' \
212                 '--version[Show package version]'
213         ;;
214         systemd-notify)
215             _arguments \
216                 {-h,--help}'[Show this help]' \
217                 '--version[Show package version]' \
218                 '--ready[Inform the init system about service start-up completion.]' \
219                 '--pid=[Inform the init system about the main PID of the daemon]' \
220                 '--status=[Send a free-form status string for the daemon to the init systemd]' \
221                 '--booted[Returns 0 if the system was booted up with systemd]' \
222                 '--readahead=[Controls disk read-ahead operations]:arguments:(cancel done noreply)'
223         ;;
224         systemd-nspawn)
225             _arguments \
226                 {-h,--help}'[Show this help]' \
227                 {--directory=,-D}'[Directory to use as file system root for the namespace container. If omitted the current directory will be used.]:directories:_directories' \
228                 {--boot,-b}'[Automatically search for an init binary and invoke it instead of a shell or a user supplied program.]' \
229                 {--user=,-u}'[Run the command under specified user, create home directory and cd into it.]' \
230                 '--uuid=[Set the specified uuid for the container.]' \
231                 {--controllers=,-C}'[Makes the container appear in other hierarchies than the name=systemd:/ one. Takes a comma-separated list of controllers.]' \
232                 '--private-network[Turn off networking in the container. This makes all network interfaces unavailable in the container, with the exception of the loopback device.]' \
233                 '--read-only[Mount the root file system read only for the container.]' \
234                 '--capability=[List one or more additional capabilities to grant the container.]:capabilities:_systemd-nspawn' \
235                 "--link-journal=[Control whether the container's journal shall be made visible to the host system.]:options:(no, host, guest, auto)" \
236                 '-j[Equivalent to --link-journal=guest.]'
237         ;;
238         systemd-tmpfiles)
239             _arguments \
240                 '--create[Create, set ownership/permissions based on the config files.]' \
241                 '--clean[Clean up all files and directories with an age parameter configured.]' \
242                 '--remove[All files and directories marked with r, R in the configuration files are removed.]' \
243                 '--prefix=[Only apply rules that apply to paths with the specified prefix.]' \
244                 '--help[Prints a short help text and exits.]' \
245                 '*::files:_files'
246         ;;
247         systemd-tty-ask-password-agent)
248             _arguments \
249                 {-h,--help}'[Prints a short help text and exits.]' \
250                 '--version[Prints a short version string and exits.]' \
251                 '--list[Lists all currently pending system password requests.]' \
252                 '--query[Process all currently pending system password requests by querying the user on the calling TTY.]' \
253                 '--watch[Continuously process password requests.]' \
254                 '--wall[Forward password requests to wall(1).]' \
255                 '--plymouth[Ask question with plymouth(8).]' \
256                 '--console[Ask question on /dev/console.]'
257         ;;
258         *) _message 'eh?' ;;
259     esac
260 }
261
262 _systemd-nspawn(){
263     local -a _caps
264     _caps=( CAP_CHOWN CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH
265             CAP_FOWNER CAP_FSETID CAP_IPC_OWNER CAP_KILL CAP_LEASE CAP_LINUX_IMMUTABLE
266             CAP_NET_BIND_SERVICE CAP_NET_BROADCAST CAP_NET_RAW CAP_SETGID CAP_SETFCAP CAP_SETPCAP
267             CAP_SETUID CAP_SYS_ADMIN CAP_SYS_CHROOT CAP_SYS_NICE CAP_SYS_PTRACE CAP_SYS_TTY_CONFIG
268             CAP_SYS_RESOURCE CAP_SYS_BOOT )
269     _values -s , 'capabilities' "$_caps[@]"
270 }
271
272 _systemd_inhibit_command(){
273     if (( CURRENT == 1 )); then 
274         compset -q
275         _normal
276     else
277         local n=${words[(b:2:i)[^-]*]}
278         if (( n <= CURRENT )); then
279             compset -n $n
280             _alternative \
281                 'files:file:_files' \
282                 'commands:command:_normal' && return 0
283         fi
284         _default
285     fi
286
287 }
288
289 _systemd_analyze_command(){
290     local -a _systemd_analyze_cmds
291     _systemd_analyze_cmds=(
292         'time:Print the time taken to start'
293         'blame:prints a list of all running units, ordered by the time they took to initialize'
294         'plot:prints an SVG graphic detailing which system services have been started at what time'
295     )
296
297     if (( CURRENT == 1 )); then
298         _describe "options" _systemd_analyze_cmds
299     else
300         _message "no more options"
301     fi
302 }
303
304 _hosts_or_user_at_host()
305 {
306   _alternative \
307     'users-hosts:: _user_at_host' \
308     'hosts:: _hosts'
309 }
310
311 _outputmodes() {
312     local -a _output_opts
313     _output_opts=(short short-monotonic verbose export json json-pretty json-see cat)
314     _describe -t output 'output mode' _output_opts || compadd "$@"
315 }
316         
317
318 (( $+functions[_systemctl_command] )) || _systemctl_command()
319 {
320   local -a _systemctl_cmds
321   _systemctl_cmds=(
322     "list-units:List units"
323     "start:Start (activate) one or more units"
324     "stop:Stop (deactivate) one or more units"
325     "reload:Reload one or more units"
326     "restart:Start or restart one or more units"
327     "condrestart:Restart one or more units if active"
328     "try-restart:Restart one or more units if active"
329     "reload-or-restart:Reload one or more units is possible, otherwise start or restart"
330     "force-reload:Reload one or more units is possible, otherwise restart if active"
331     "reload-or-try-restart:Reload one or more units is possible, otherwise restart if active"
332     "isolate:Start one unit and stop all others"
333     "kill:Send signal to processes of a unit"
334     "is-active:Check whether units are active"
335     "status:Show runtime status of one or more units"
336     "show:Show properties of one or more units/jobs or the manager"
337     "reset-failed:Reset failed state for all, one, or more units"
338     "load:Load one or more units"
339     "list-unit-files:List installed unit files"
340     "enable:Enable one or more unit files"
341     "disable:Disable one or more unit files"
342     "reenable:Reenable one or more unit files"
343     "preset:Enable/disable one or more unit files based on preset configuration"
344     "mask:Mask one or more units"
345     "unmask:Unmask one or more units"
346     "link:Link one or more units files into the search path"
347     "is-enabled:Check whether unit files are enabled"
348     "list-jobs:List jobs"
349     "cancel:Cancel all, one, or more jobs"
350     "dump:Dump server status"
351     "dot:Dump dependency graph for dot(1)"
352     "snapshot:Create a snapshot"
353     "delete:Remove one or more snapshots"
354     "show-environment:Dump environment"
355     "set-environment:Set one or more environment variables"
356     "unset-environment:Unset one or more environment variables"
357     "daemon-reload:Reload systemd manager configuration"
358     "daemon-reexec:Reexecute systemd manager"
359     "default:Enter system default mode"
360     "rescue:Enter system rescue mode"
361     "emergency:Enter system emergency mode"
362     "halt:Shut down and halt the system"
363     "suspend:Suspend the system"
364     "poweroff:Shut down and power-off the system"
365     "reboot:Shut down and reboot the system"
366     "kexec:Shut down and reboot the system with kexec"
367     "exit:Ask for user instance termination"
368   )
369
370   if (( CURRENT == 1 )); then
371     _describe -t commands 'systemctl command' _systemctl_cmds || compadd "$@"
372   else
373     local curcontext="$curcontext"
374
375     cmd="${${_systemctl_cmds[(r)$words[1]:*]%%:*}}"
376     # Deal with any aliases
377     case $cmd in
378       condrestart) cmd="try-restart";;
379       force-reload) cmd="reload-or-try-restart";;
380     esac
381
382     if (( $#cmd )); then
383       curcontext="${curcontext%:*:*}:systemctl-${cmd}:"
384
385       local update_policy
386       zstyle -s ":completion:${curcontext}:" cache-policy update_policy
387       if [[ -z "$update_policy" ]]; then
388         zstyle ":completion:${curcontext}:" cache-policy _systemctl_caching_policy
389       fi
390
391       _call_function ret _systemctl_$cmd || _message 'no more arguments'
392     else
393       _message "unknown systemctl command: $words[1]"
394     fi
395     return ret
396   fi
397 }
398
399 __systemctl()
400 {
401   systemctl --full --no-legend --no-pager "$@"
402 }
403
404
405 # Fills the unit list
406 _systemctl_all_units()
407 {
408   if ( [[ ${+_sys_all_units} -eq 0 ]] || _cache_invalid SYS_ALL_UNITS ) &&
409     ! _retrieve_cache SYS_ALL_UNITS;
410   then
411     _sys_all_units=( $(__systemctl list-units --all | { while read a b; do echo "$a"; done; }) )
412     _store_cache SYS_ALL_UNITS _sys_all_units
413   fi
414 }
415
416 # Fills the unit list including all file units
417 _systemctl_really_all_units()
418 {
419   local -a all_unit_files;
420   local -a really_all_units;
421   if ( [[ ${+_sys_really_all_units} -eq 0 ]] || _cache_invalid SYS_REALLY_ALL_UNITS ) &&
422     ! _retrieve_cache SYS_REALLY_ALL_UNITS;
423   then
424     all_unit_files=( $(__systemctl list-unit-files | { while read a b; do echo "$a"; done; }) )
425     _systemctl_all_units
426     really_all_units=($_sys_all_units $all_unit_files)
427     _sys_really_all_units=(${(u)really_all_units})
428     _store_cache SYS_REALLY_ALL_UNITS _sys_really_all_units
429   fi
430 }
431
432 _filter_units_by_property() {
433   local property=$1 value=$2 ; shift ; shift
434   local -a units ; units=($*)
435   local prop unit
436   for ((i=1; $i <= ${#units[*]}; i++)); do
437     # FIXME: "Failed to issue method call: Unknown unit" errors are ignored for
438     # now (related to DBUS_ERROR_UNKNOWN_OBJECT). in the future, we need to
439     # revert to calling 'systemctl show' once for all units, which is way
440     # faster
441     unit=${units[i]}
442     prop=${(f)"$(_call_program units "$service show --no-pager --property="$property" ${unit} 2>/dev/null")"}
443     if [[ "${prop}" = "$property=$value" ]]; then
444       echo "${unit}"
445     fi
446   done
447 }
448
449 _systemctl_active_units()  {_sys_active_units=(  $(__systemctl list-units          | { while read a b; do echo "$a"; done; }) )}
450 _systemctl_inactive_units(){_sys_inactive_units=($(__systemctl list-units --all    | { while read a b c d; do [[ $c == "inactive" ]] && echo "$a"; done; }) )}
451 _systemctl_failed_units()  {_sys_failed_units=(  $(__systemctl list-units --failed | { while read a b; do echo "$a"; done; }) )}
452 _systemctl_enabled_units() {_sys_enabled_units=( $(__systemctl list-unit-files     | { while read a b; do [[ $b == "enabled" ]] && echo "$a"; done; }) )}
453 _systemctl_disabled_units(){_sys_disabled_units=($(__systemctl list-unit-files     | { while read a b; do [[ $b == "disabled" ]] && echo "$a"; done; }) )}
454 _systemctl_masked_units()  {_sys_masked_units=(  $(__systemctl list-unit-files     | { while read a b; do [[ $b == "masked" ]] && echo "$a"; done; }) )}
455
456 # Completion functions for ALL_UNITS
457 for fun in is-active is-enabled status show mask preset ; do
458   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
459   {
460     _systemctl_really_all_units
461     compadd "$@" -a - _sys_really_all_units
462   }
463 done
464
465 # Completion functions for ENABLED_UNITS
466 for fun in disable reenable ; do
467   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
468   {
469     _systemctl_enabled_units
470     compadd "$@" -a - _sys_enabled_units
471   }
472 done
473
474 # Completion functions for DISABLED_UNITS
475 (( $+functions[_systemctl_enable] )) || _systemctl_enable()
476 {
477   _systemctl_disabled_units
478   compadd "$@" -a - _sys_disabled_units
479 }
480
481 # Completion functions for FAILED_UNITS
482 (( $+functions[_systemctl_reset-failed] )) || _systemctl_reset-failed()
483 {
484   _systemctl_failed_units
485   compadd "$@" -a - _sys_failed_units || _message "no failed unit found"
486 }
487
488 # Completion functions for STARTABLE_UNITS
489 (( $+functions[_systemctl_start] )) || _systemctl_start()
490 {
491   _systemctl_inactive_units
492   compadd "$@" -a - _sys_inactive_units
493 }
494
495 # Completion functions for STOPPABLE_UNITS
496 for fun in stop kill try-restart condrestart ; do
497   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
498   {
499     _systemctl_active_units
500     compadd "$@" - $( _filter_units_by_property CanStop yes \
501       ${_sys_active_units[*]} )
502   }
503 done
504
505 # Completion functions for ISOLATABLE_UNITS
506 (( $+functions[_systemctl_isolate] )) || _systemctl_isolate()
507 {
508   _systemctl_all_units
509   compadd "$@" - $( _filter_units_by_property AllowIsolate yes \
510     ${_sys_all_units[*]} )
511 }
512
513 # Completion functions for RELOADABLE_UNITS
514 for fun in reload reload-or-try-restart force-reload ; do
515   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
516   {
517     _systemctl_active_units
518     compadd "$@" - $( _filter_units_by_property CanReload yes \
519       ${_sys_active_units[*]} )
520   }
521 done
522
523 # Completion functions for RESTARTABLE_UNITS
524 for fun in restart reload-or-restart ; do
525   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
526   {
527     _systemctl_all_units
528     compadd "$@" - $( _filter_units_by_property CanStart yes \
529       ${_sys_all_units[*]} | while read line; do \
530       [[ "$line" =~ \.(device|snapshot|socket|timer)$ ]] || echo "$line"; \
531       done )
532   }
533 done
534
535 # Completion functions for MASKED_UNITS
536 (( $+functions[_systemctl_unmask] )) || _systemctl_unmask()
537 {
538   _systemctl_masked_units
539   compadd "$@" -a - _sys_masked_units || _message "no masked unit found"
540 }
541
542 # Completion functions for JOBS
543 (( $+functions[_systemctl_cancel] )) || _systemctl_cancel()
544 {
545   compadd "$@" - $(__systemctl list-jobs \
546     | cut -d' ' -f1  2>/dev/null ) || _message "no job found"
547 }
548
549 # Completion functions for SNAPSHOTS
550 (( $+functions[_systemctl_delete] )) || _systemctl_delete()
551 {
552   compadd "$@" - $(__systemctl list-units --type snapshot --all \
553     | cut -d' ' -f1  2>/dev/null ) || _message "no snampshot found"
554 }
555
556 # Completion functions for ENVS
557 for fun in set-environment unset-environment ; do
558   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
559   {
560     local fun=$0 ; fun=${fun##_systemctl_}
561     local suf
562     if [[ "${fun}" = "set-environment" ]]; then
563       suf='-S='
564     fi
565
566     compadd "$@" ${suf} - $(systemctl show-environment \
567       | while read line; do echo "${line%%\=}";done )
568   }
569 done
570
571 (( $+functions[_systemctl_link] )) || _systemctl_link() { _files }
572
573 # no systemctl completion for:
574 #    [STANDALONE]='daemon-reexec daemon-reload default dot dump
575 #                  emergency exit halt kexec list-jobs list-units
576 #                  list-unit-files poweroff reboot rescue show-environment'
577 #         [NAME]='snapshot load'
578
579 _systemctl_caching_policy()
580 {
581   local _sysunits
582   local -a oldcache
583
584   # rebuild if cache is more than a day old
585   oldcache=( "$1"(mh+1) )
586   (( $#oldcache )) && return 0
587
588   _sysunits=($(__systemctl --all | cut -d' ' -f1))
589
590   if (( $#_sysunits )); then
591     for unit in $_sysunits; do
592       [[ "$unit" -nt "$1" ]] && return 0
593     done
594   fi
595
596   return 1
597 }
598
599 _list_fields() {
600     local -a journal_fields
601     journal_fields=(MESSAGE{,_ID} PRIORITY CODE_{FILE,LINE,FUNC}
602                     ERRNO SYSLOG_{FACILITY,IDENTIFIER,PID}
603                     _{P,U,G}ID _COMM _EXE _CMDLINE
604                     _AUDIT_{SESSION,LOGINUID}
605                     _SYSTEMD_{CGROUP,SESSION,UNIT,OWNER_UID}
606                     _SELINUX_CONTEXT _SOURCE_REALTIME_TIMESTAMP
607                     _{BOOT,MACHINE}_ID _HOSTNAME _TRANSPORT
608                     _KERNEL_{DEVICE,SUBSYSTEM}
609                     _UDEV_{SYSNAME,DEVNODE,DEVLINK}
610                     __CURSOR __{REALTIME,MONOTONIC}_TIMESTAMP)
611     _describe 'possible fields' journal_fields
612 }
613
614 _journal_fields() {
615     local -a _fields cmd
616     cmd=("journalctl" "-F ${@[-1]}" "2>/dev/null" )
617     _fields=( ${(f)"$(_call_program fields $cmd[@])"} ) 
618     typeset -U _fields
619     _describe 'possible values' _fields
620 }
621
622
623 _loginctl_all_sessions(){_sys_all_sessions=($(loginctl list-sessions | { while read a b; do echo "$a"; done; }) )}
624 _loginctl_all_users()   {_sys_all_users=(   $(loginctl list-users    | { while read a b; do echo "$a"; done; }) )}
625 _loginctl_all_seats()   {_sys_all_seats=(   $(loginctl list-seats    | { while read a b; do echo "$a"; done; }) )}
626
627 # Completion functions for SESSIONS
628 for fun in session-status show-session activate lock-session unlock-session terminate-session kill-session ; do
629   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
630   {
631     _loginctl_all_sessions
632     compadd "$@" -a - _sys_all_sessions
633   }
634 done
635
636 # Completion functions for USERS
637 for fun in user-status show-user enable-linger disable-linger terminate-user kill-user ; do
638   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
639   {
640     _loginctl_all_users
641     compadd "$@" -a - _sys_all_users
642   }
643 done
644
645 # Completion functions for SEATS
646 (( $+functions[_loginctl_seats] )) || _loginctl_seats()
647 {
648   _loginctl_all_seats
649   compadd "$@" -a - _sys_all_seats
650 }
651 for fun in seat-status show-seat terminate-seat ; do
652   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
653   { _loginctl_seats }
654 done
655
656 # Completion functions for ATTACH
657 (( $+functions[_loginctl_attach] )) || _loginctl_attach()
658 {
659   _loginctl_all_seats
660
661   _arguments -w -C -S -s \
662     ':seat:_loginctl_seats' \
663     '*:device:_files'
664 }
665
666 # no loginctl completion for:
667 # [STANDALONE]='list-sessions list-users list-seats flush-devices'
668
669 (( $+functions[_loginctl_command] )) || _loginctl_command()
670 {
671   local -a _loginctl_cmds
672   _loginctl_cmds=(
673     "list-sessions:List sessions"
674     "session-status:Show session status"
675     "show-session:Show properties of one or more sessions"
676     "activate:Activate a session"
677     "lock-session:Screen lock one or more sessions"
678     "unlock-session:Screen unlock one or more sessions"
679     "terminate-session:Terminate one or more sessions"
680     "kill-session:Send signal to processes of a session"
681     "list-users:List users"
682     "user-status:Show user status"
683     "show-user:Show properties of one or more users"
684     "enable-linger:Enable linger state of one or more users"
685     "disable-linger:Disable linger state of one or more users"
686     "terminate-user:Terminate all sessions of one or more users"
687     "kill-user:Send signal to processes of a user"
688     "list-seats:List seats"
689     "seat-status:Show seat status"
690     "show-seat:Show properties of one or more seats"
691     "attach:Attach one or more devices to a seat"
692     "flush-devices:Flush all device associations"
693     "terminate-seat:Terminate all sessions on one or more seats"
694   )
695
696   if (( CURRENT == 1 )); then
697     _describe -t commands 'loginctl command' _loginctl_cmds || compadd "$@"
698   else
699     local curcontext="$curcontext"
700
701     cmd="${${_loginctl_cmds[(r)$words[1]:*]%%:*}}"
702
703     if (( $#cmd )); then
704       curcontext="${curcontext%:*:*}:loginctl-${cmd}:"
705
706       _call_function ret _loginctl_$cmd || _message 'no more arguments'
707     else
708       _message "unknown loginctl command: $words[1]"
709     fi
710     return ret
711   fi
712 }
713
714 _hostnamectl_command() {
715     local -a _hostnamectl_cmds
716     _hostnamectl_cmds=(
717         "status:Show current hostname settings"
718         "set-hostname:Set system hostname"
719         "set-icon-name:Set icon name for host"
720     )
721     if (( CURRENT == 1 )); then
722         _describe -t commands 'hostnamectl commands' _hostnamectl_cmds || compadd "$@"
723     else
724         local curcontext="$curcontext"
725         cmd="${${_hostnamectl_cmds[(r)$words[1]:*]%%:*}}"
726         if (( $#cmd )); then
727             [[ $cmd == status ]] && msg="no options" || msg="options for $cmd"
728             _message "$msg"
729         else
730             _message "unknown hostnamectl command: $words[1]"
731         fi
732     fi
733 }
734
735 _localectl_set-locale() {
736     local -a _confs _locales
737     local expl suf
738     _locales=( ${(f)"$(_call_program locales "$service" list-locales)"} )
739     _confs=( ${${(f)"$(_call_program confs "locale 2>/dev/null")"}%\=*} )
740     if [[ -prefix 1 *\= ]]; then
741         local conf=${PREFIX%%\=*}
742         compset -P1 '*='
743         _wanted locales expl "locales configs" \
744             _combination localeconfs  confs=$conf locales "$@" -
745     else
746         compadd -S '='  $_confs
747     fi
748 }
749
750 _localectl_set-keymap() {
751     local -a _keymaps
752     _keymaps=( ${(f)"$(_call_program locales "$service" list-keymaps)"} )
753     if (( CURRENT <= 3 )); then
754         _describe keymaps _keymaps
755     else
756         _message "no more options"
757     fi
758 }
759
760 _localectl_set-x11-keymap() {
761     if (( $+commands[pkg-config] )); then
762         local -a _file _layout _model _variant _options
763         local _xorg_lst
764         _xorg_lst=${"$($commands[pkg-config] xkeyboard-config --variable=xkb_base)"}
765         _file=( ${(ps:\n\!:)"$(<$_xorg_lst/rules/xorg.lst)"} )
766         _layout=( ${${${(M)${(f)_file[1]}:#  *}#  }%% *} )
767         _model=( ${${${(M)${(f)_file[2]}:#  *}#  }%% *} )
768         _variant=( ${${${(M)${(f)_file[3]}:#  *}#  }%% *} )
769         _options=( ${${${(M)${(f)_file[4]}:#  *}#  }%% *} )
770         #_layout=( ${(f)"$( echo $_file[1] | awk '/^  / {print $1}' )"} )
771         #_model=( ${(f)"$(echo $_file[2] | awk '/^  / {print $1}')"} )
772         #_variant=( ${(f)"$(echo $_file[3] | awk '/^  / {print $1}')"} )
773         #_options=( ${(f)"$(echo ${_file[4]//:/\\:} | awk '/^  / {print $1}')"} )
774         
775         case $CURRENT in 
776             2) _describe layouts _layout ;;
777             3) _describe models _model;;
778             4) _describe variants _variant;;
779             5) _describe options _options;;
780             *) _message "no more options"
781         esac
782     fi
783 }
784
785
786 _localectl_command() {
787     local -a _localectl_cmds
788     _localectl_cmds=(
789         'status:Show current locale settings'
790         'set-locale:Set system locale'
791         'list-locales:Show known locales'
792         'set-keymap:Set virtual console keyboard mapping'
793         'list-keymaps:Show known virtual console keyboard mappings'
794         'set-x11-keymap:Set X11 keyboard mapping'
795     )
796     if (( CURRENT == 1 )); then
797         _describe -t commands 'localectl command' _localectl_cmds
798     else
799         local curcontext="$curcontext"
800         cmd="${${_localectl_cmds[(r)$words[1]:*]%%:*}}"
801         if (( $+functions[_localectl_$cmd] )); then
802             _localectl_$cmd
803         else
804             _message "no more options"
805         fi
806     fi
807 }
808
809 _timedatectl_set-timezone(){
810     local -a _timezones
811     _timezones=( ${(f)"$(_call_program timezones "${service}" list-timezones)"} )
812     compadd "$_timezones[@]"
813 }
814
815 _timedatectl_set-time(){
816     _message "YYYY-MM-DD HH:MM:SS"
817 }
818
819 _timedatectl_set-local-rtc(){
820     local -a _options
821     _options=(
822         '0:Maintain RTC in universal time'
823         '1:Maintain RTC in local time'
824     )
825     _describe options _options
826 }
827
828 _timedatectl_set-ntp(){
829     local -a _options
830     _options=(
831         '0:Disable NTP based network time configuration'
832         '1:Enable NTP based network time configuration'
833     )
834     _describe options _options
835 }
836
837 _timedatectl_command(){
838     local -a _timedatectl_cmds
839     _timedatectl_cmds=(
840         'status:Show current time settings'
841         'set-time:Set system time'
842         'set-timezone:Set system timezone'
843         'list-timezones:Show known timezones'
844         'set-local-rtc:Control whether RTC is in local time'
845         'set-ntp:Control whether NTP is enabled'
846     )
847     if (( CURRENT == 1 )); then
848         _describe -t commands 'timedatectl command' _timedatectl_cmds
849     else
850         local curcontext="$curcontext"
851         cmd="${${_timedatectl_cmds[(r)$words[1]:*]%%:*}}"
852         if (( $#cmd )); then
853             if (( $+functions[_timedatectl_$cmd] )); then
854                 _timedatectl_$cmd
855             else
856                 _message "no more options"
857             fi
858         else
859             _message "unknown timedatectl command: $words[1]"
860         fi
861     fi
862 }
863 _systemd-coredumpctl_command(){
864     local -a _systemd_coredumpctl_cmds
865     _systemd_coredumpctl_cmds=(
866             'list:List available coredumps'
867             'dump:Print coredump to std'
868     )
869     if (( CURRENT == 1 )); then
870         _describe -t commands 'systemd-coredumpctl command' _systemd_coredumpctl_cmds
871     else
872         local curcontext="$curcontext"
873         local -a dumps
874         cmd="${${_systemd_coredumpctl_cmds[(r)$words[1]:*]%%:*}}"
875         if (( $#cmd  )); then
876             dumps=( "${(f)$(_call_program dumps "systemd-coredumpctl list 2>/dev/null")}" )
877             if [[ -n "$dumps" ]]; then
878                 compadd "${dumps[@]}"
879             else
880                 _message "no coredumps"
881             fi
882         else
883             _message "no more options"
884         fi
885
886     fi
887
888 }
889
890 _udevadm_info(){
891     _arguments \
892         '--query=[Query the database for specified type of device data. It needs the --path or --name to identify the specified device.]:type:(name symlink path property all)' \
893         '--path=[The devpath of the device to query.]:sys files:_files -P /sys/ -W /sys' \
894         '--name=[The name of the device node or a symlink to query]:device files:_files -P /dev/ -W /dev' \
895         '--root[Print absolute paths in name or symlink query.]' \
896         '--attribute-walk[Print all sysfs properties of the specified device that can be used in udev rules to match the specified device]' \
897         '--export[Print output as key/value pairs.]' \
898         '--export-prefix=[Add a prefix to the key name of exported values.]:prefix' \
899         '--device-id-of-file=[Print major/minor numbers of the underlying device, where the file lives on.]:files:_udevadm_mounts' \
900         '--export-db[Export the content of the udev database.]' \
901         '--cleanup-db[Cleanup the udev database.]'
902 }
903
904 _udevadm_trigger(){
905     _arguments \
906         '--verbose[Print the list of devices which will be triggered.]' \
907         '--dry-run[Do not actually trigger the event.]' \
908         '--type=[Trigger a specific type of devices.]:types:(devices subsystems failed)' \
909         '--action=[Type of event to be triggered.]:actions:(add change remove)' \
910         '--subsystem-match=[Trigger events for devices which belong to a matching subsystem.]' \
911         '--subsystem-nomatch=[Do not trigger events for devices which belong to a matching subsystem.]' \
912         '--attr-match=attribute=[Trigger events for devices with a matching sysfs attribute.]' \
913         '--attr-nomatch=attribute=[Do not trigger events for devices with a matching sysfs attribute.]' \
914         '--property-match=[Trigger events for devices with a matching property value.]' \
915         '--tag-match=property[Trigger events for devices with a matching tag.]' \
916         '--sysname-match=[Trigger events for devices with a matching sys device name.]' \
917         '--parent-match=[Trigger events for all children of a given device.]'
918 }
919
920 _udevadm_settle(){
921     _arguments \
922        '--timeout=[Maximum number of seconds to wait for the event queue to become empty.]' \
923        '--seq-start=[Wait only for events after the given sequence number.]' \
924        '--seq-end=[Wait only for events before the given sequence number.]' \
925        '--exit-if-exists=[Stop waiting if file exists.]:files:_files' \
926        '--quiet[Do not print any output, like the remaining queue entries when reaching the timeout.]' \
927        '--help[Print help text.]'
928 }
929
930 _udevadm_control(){
931     _arguments \
932         '--exit[Signal and wait for systemd-udevd to exit.]' \
933         '--log-priority=[Set the internal log level of systemd-udevd.]:priorities:(err info debug)' \
934         '--stop-exec-queue[Signal systemd-udevd to stop executing new events. Incoming events will be queued.]' \
935         '--start-exec-queue[Signal systemd-udevd to enable the execution of events.]' \
936         '--reload[Signal systemd-udevd to reload the rules files and other databases like the kernel module index.]' \
937         '--property=[Set a global property for all events.]' \
938         '--children-max=[Set the maximum number of events.]' \
939         '--timeout=[The maximum number of seconds to wait for a reply from systemd-udevd.]' \
940         '--help[Print help text.]'
941 }
942  
943 _udevadm_monitor(){
944     _arguments \
945         '--kernel[Print the kernel uevents.]' \
946         '--udev[Print the udev event after the rule processing.]' \
947         '--property[Also print the properties of the event.]' \
948         '--subsystem-match=[Filter events by subsystem[/devtype].]' \
949         '--tag-match=[Filter events by property.]' \
950         '--help[Print help text.]'
951 }
952
953 _udevadm_test(){
954     _arguments \
955         '--action=[The action string.]:actions:(add change remove)' \
956         '--subsystem=[The subsystem string.]' \
957         '--help[Print help text.]' \
958         '*::devpath:_files -P /sys/ -W /sys'
959 }
960
961 _udevadm_test-builtin(){
962     if (( CURRENT == 2 )); then
963     _arguments \
964         '--help[Print help text]' \
965         '*::builtins:(blkid btrfs firmware hwdb input_id kmod path_id usb_id uaccess)'
966     elif  (( CURRENT == 3 )); then
967         _arguments \
968             '--help[Print help text]' \
969             '*::syspath:_files -P /sys -W /sys'
970     else
971         _arguments \
972             '--help[Print help text]'
973     fi
974 }
975
976 _udevadm_mounts(){
977   local dev_tmp dpath_tmp mp_tmp mline
978
979     tmp=( "${(@f)$(< /etc/mtab)}" )
980     dev_tmp=( "${(@)${(@)tmp%% *}:#none}" )
981     mp_tmp=( "${(@)${(@)tmp#* }%% *}" )
982
983   local MATCH
984   mp_tmp=("${(@q)mp_tmp//(#m)\\[0-7](#c3)/${(#)$(( 8#${MATCH[2,-1]} ))}}")
985   dpath_tmp=( "${(@Mq)dev_tmp:#/*}" )
986   dev_tmp=( "${(@q)dev_tmp:#/*}" )
987
988   _alternative \
989     'device-paths: device path:compadd -a dpath_tmp' \
990     'directories:mount point:compadd -a mp_tmp'
991 }
992
993
994 _udevadm_command(){
995     local -a _udevadm_cmds
996     _udevadm_cmds=(
997         'info:query sysfs or the udev database'
998         'trigger:request events from the kernel'
999         'settle:wait for the event queue to finish'
1000         'control:control the udev daemon'
1001         'monitor:listen to kernel and udev events'
1002         'test:test an event run'
1003         'test-builtin:test a built-in command'
1004     )
1005
1006     if ((CURRENT == 1)); then
1007         _describe -t commands 'udevadm commands' _udevadm_cmds
1008     else
1009         local curcontext="$curcontext"
1010         cmd="${${_udevadm_cmds[(r)$words[1]:*]%%:*}}"
1011         if (($#cmd)); then
1012             if (( $+functions[_udevadm_$cmd] )); then
1013                 _udevadm_$cmd
1014             else
1015                 _message "no options for $cmd"
1016             fi
1017         else
1018             _message "no more options"
1019         fi
1020     fi
1021 }
1022
1023 _ctls "$@"
1024
1025 #vim: set ft=zsh sw=4 ts=4 et