# Wireless connection support for netctl

. "$SUBR_DIR/ip"
. "$SUBR_DIR/wpa"
. "$SUBR_DIR/rfkill"


wireless_up() {
    local config_file

    if ! is_interface "$Interface"; then
        report_error "Interface '$Interface' does not exist"
        return 1
    fi

    # Default settings
    : ${Security:=none}
    : ${WPADriver:=nl80211,wext}
    : ${TimeoutWPA:=15}

    if [[ $RFKill ]]; then
        rf_enable "$Interface" "$RFKill" || return 1
    fi

    # Kill any lingering WPA supplicants
    WPAConfigFile="" wpa_stop "$Interface" &> /dev/null

    if [[ $Security == "wpa-config" ]]; then
        : ${WPAConfigFile:=/etc/wpa_supplicant.conf}
        config_file=$WPAConfigFile
    else
        # Remove any stray configuration files
        wpa_destroy_config_file "$Interface"
        config_file=$(wpa_make_config_file "$Interface")
        if [[ -z $config_file ]]; then
            report_error "Could not create a WPA config file for interface '$Interface'"
            return 1
        fi
        printf "%s\n" "network={" "$(wpa_make_config_block)" "}" >> "$config_file"
    fi

    # Start the WPA supplicant
    if ! wpa_start "$Interface" "$WPADriver" "$config_file"; then
        report_error "The WPA supplicant did not start for interface '$Interface'"
        if [[ $Security != "wpa-config" ]]; then
            wpa_destroy_config_file "$Interface"
        fi
        bring_interface_down "$Interface"
        return 1
    fi

    # Bring interface up after starting wpa_supplicant
    # This is important since cards such as iwl3945 do not support
    # mode switching when they are already up.
    if ! bring_interface_up "$Interface" ||
       ! wpa_wait_until_completed "$TimeoutWPA" "$Interface" ||
       ! ip_set; then
        wpa_stop "$Interface"
        if [[ $Security != "wpa-config" ]]; then
            wpa_destroy_config_file "$Interface"
        fi
        bring_interface_down "$Interface"
        return 1
    fi
}

wireless_down() {
    ip_unset
    if [[ $Security == "wpa-config" ]]; then
        : ${WPAConfigFile:=/etc/wpa_supplicant.conf}
    else
        wpa_destroy_config_file "$Interface"
    fi
    wpa_stop "$Interface"
    bring_interface_down "$Interface" || return 1
    if [[ $RFKill ]]; then
        rf_disable "$Interface" "$RFKill"
    fi
}


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