#! /bin/bash
#
# ifplugd.action script for netctl

. /usr/lib/netctl/globals

PROFILE_FILE="$STATE_DIR/ifplugd-$1.profile"

case "$2" in
  up)
    while IFS= read -r profile; do
        if ForceConnect=yes "$SUBR_DIR/network" start "$profile"; then
            mkdir -p "$(dirname "$PROFILE_FILE")"
            printf '%s' "$profile" > "$PROFILE_FILE"
            exit 0
        fi
    done < <(list_profiles | while IFS= read -r profile; do
        report_debug "Examining profile '$profile'"
        (
          source "$PROFILE_DIR/$profile" > /dev/null
          [[ $Interface == "$1" && $Connection == "ethernet" ]] || exit
          # Prioritize dhcp based profiles as they can outright fail, whereas
          # it is difficult to tell if a profile with a static address fails
          if [[ $IP == "dhcp" || $IP6 == dhcp* ]]; then
              : ${ExcludeAuto:=no}
              : ${Priority:=1}
          fi
          is_yes "${ExcludeAuto:-yes}" && exit
          printf '%i\t%s\n' "${Priority:-0}" "$profile"
          report_debug "Included profile '$profile'"
        )
    done | sort -nrs -k 1,1 | cut -f 2-)
    report_error "Could not start any suitable profile"
  ;;
  down)
    if [[ -e "$PROFILE_FILE" ]]; then
        if ForceConnect=yes "$SUBR_DIR/network" stop "$(< "$PROFILE_FILE")"; then
            rm -f "$PROFILE_FILE"
            exit 0
        fi
    fi
  ;;
  *)
    echo "Wrong arguments" >&2
  ;;
esac

exit 1


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