#!/bin/bash

. /usr/lib/network/globals

case "$1" in
    start)
        if ! ck_daemon net-auto; then           # JP: check if it's already running
            exit_stderr "net-auto has already been started: try \"/etc/rc.d/net-auto restart\""
        fi
        # Ensure any device renaming has occurred as intended
        for daemon in "${DAEMONS[@]}"; do
            if [[ "$daemon" = "${daemon#!}" && "$daemon" = "net-rename" ]]; then
                if ck_daemon net-rename; then
                    /etc/rc.d/net-rename start
                fi
          fi
        done

        # TODO: check if any way of using 'stacks' in bash
        rm -f "$STATE_DIR/net-auto"
        for iface in "${AUTO_NETWORKS[@]}"; do
            if [[ "${iface:0:4}" = "auto" ]]; then
                auto="$iface"
            elif [[ -n "$auto" ]]; then
                if /usr/bin/netcfg-"$auto" "$iface"; then
                    echo "$iface" >> "$STATE_DIR/net-auto"
                    add_daemon net-auto             # JP: was this forgotten?
                fi
                unset auto
            fi
        done
        ;;
    stop)
        if ck_daemon net-auto; then
            exit_stderr "net-auto not running"
        fi

        for iface in $(cat "$STATE_DIR/net-auto"); do
            /usr/bin/netcfg2 iface-down "$iface"
        done
        rm -f "$STATE_DIR/net-auto"
        rm_daemon net-auto
        ;;
    restart)
        "$0" stop; sleep 1; "$0" start
        ;;
    *)
        exit_stderr "Usage: $0 {start|stop|restart}"
esac

# vim: ft=sh ts=4 et sw=4:
