#!/bin/bash

set -e

# Source debconf library.
. /usr/share/debconf/confmodule

# Fix upgrades from broken experimental version
db_get wicd/users
if [ -n "$( echo $RET | grep \${ )" ]; then
	db_set wicd/users ""
	db_fset wicd/users seen false
fi

db_metaget wicd/users users
users="$(getent passwd | awk -F: '{if ($3 >= 1000 && $3 < 60000) print $1}' | sort | tr '\n' ',' | sed 's@,@, @g;s@, $@@g')"
netdev=$(getent group netdev | cut -d: -f4 | sed -e 's@,@ @g')

# Don't show users already in netdev
for u in $netdev; do
	users=$(echo $users | sed "s@$u, @@g;s@, $u\$@@g;s@^$u\$@@g");
done

db_subst wicd/users users "$users"

db_input high wicd/users || true
db_go

db_get wicd/users
users=$(echo $RET | sed -e 's@,@@g')

# Add selected users
for u in $users; do
	hasuser=$((getent passwd | grep -w $u) || true)
	if [ -n "$hasuser" ]; then
		adduser --quiet $u netdev
	fi
done
