#!/bin/bash

NEWROOT=${NEWROOT:-"/sysroot"}

for netup in /tmp/net.*.did-setup ; do
    [ -f $netup ] || continue

    netif=${netup%%.did-setup}
    netif=${netif##*/net.}

    [ -f /tmp/wireless-$netif ] || continue

    . /tmp/wireless-$netif

    if [ ! -f $NEWROOT/etc/sysconfig/network/ifcfg-$netif ] ; then
        {
        # create new ifcfg-wlan if it does not exist
        echo "# Generated by dracut initrd"
        echo "# ALLOW_UPDATE_FROM_INITRD"

        echo "NAME='$netif'"
        echo "STARTMODE='auto'"

        local bootproto="static"
        if [ -f /tmp/leaseinfo.${netif}.dhcp.ipv6 ]; then
            bootproto="dhcp6"
        fi
        if [ -f /tmp/leaseinfo.${netif}.dhcp.ipv4 ]; then
            if [ "$bootproto" = "dhcp6" ]; then
                bootproto="dhcp"
            else
                bootproto="dhcp4"
            fi
        fi

        echo "BOOTPROTO='$bootproto'"

        if [ "$bootproto" = "static" ]; then
            # If we've booted with static ip= lines, the override file is there
            [ -e /tmp/net.$netif.override ] && . /tmp/net.$netif.override
            echo "IPADDR='$ip'"
            if [ -n "$mask" ]; then
                if strstr "$mask" "."; then
                    echo "NETMASK='$mask'"
                else
                    echo "PREFIXLEN='$mask'"
                fi
            fi
            if [ -n "$gw" ]; then
                echo "GATEWAY='$gw'"
            fi
        fi
        [ -n "$mtu" ] && echo "MTU='$mtu'"

        echo "WIRELESS_AUTH_MODE='psk'"
        echo "WIRELESS_ESSID=$WIRELESS_ESSID"
        echo "WIRELESS_WPA_PSK=$WIRELESS_WPA_PSK"

        } > $NEWROOT/etc/sysconfig/network/ifcfg-$netif
    else
        # update existing ifcfg-wlan only if it is allowed
        # we don't want to overwrite files managed by salt
        if grep -q "ALLOW_UPDATE_FROM_INITRD" $NEWROOT/etc/sysconfig/network/ifcfg-$netif ; then
            sed -i "/^WIRELESS_ESSID=/{h;s/=.*/='$WIRELESS_ESSID'/};\${x;/^\$/{s//WIRELESS_ESSID='$WIRELESS_ESSID'/;H};x}" $NEWROOT/etc/sysconfig/network/ifcfg-$netif
            sed -i "/^WIRELESS_WPA_PSK=/{h;s/=.*/='$WIRELESS_WPA_PSK'/};\${x;/^\$/{s//WIRELESS_WPA_PSK='$WIRELESS_WPA_PSK'/;H};x}" $NEWROOT/etc/sysconfig/network/ifcfg-$netif
        fi
    fi
done
