#!/usr/bin/env bash

set -ue

DEFAULT_GROUPS='adm,cdrom,sudo,dip,plugdev'
DEFAULT_UID='1000'

echo 'Waiting for systemd to start...'
timeout 25 bash -c 'while ! systemctl is-system-running 2> /dev/null | grep -E "running|degraded" > /dev/null; do sleep 1; done' \
  || echo "[-] WARNING: timed out waiting for systemd to start"

if getent passwd "$DEFAULT_UID" > /dev/null ; then
  echo 'User account already exists, skipping creation'
  exit 0
fi

echo 'Please create a default Kali WSL user.'
echo 'The username does not need to match your Windows username.'
echo 'For more information visit: https://aka.ms/wslusers'

while true; do
  ## Prompt from the username
  read -r -p 'Enter new UNIX username: ' username

  ## Create the user
  if /usr/sbin/adduser --uid "${DEFAULT_UID}" --quiet --gecos '' "${username}"; then
    if /usr/sbin/usermod -aG "${DEFAULT_GROUPS}" "${username}"; then
      break
    else
      /usr/bin/deluser "${username}"
    fi
  fi
done
