#!/usr/bin/env bash

domain='exotic.sh'
group="$(echo $domain | awk -F. '{printf $1}')"

cmd="$1"
user="$2"
email="$3"
ssh_pubkey="$4"

die() {
    echo "$@" >&2; exit 1;
}

confirm() {
    printf '%s\n' "$@"
    select yn in "Yes" "No"; do
      case $yn in
        Yes) return 0; break;;
        No) return 1; break;;
      esac;
    done
}

help() {
    printf '%s user management\n\n' $domain
    printf 'Usage: %s [args]\n' "$(basename "$0")"
    printf '\tadd <user> <email> <ssh-pubkey> - add user\n'
    printf '\tdel <user> - delete user\n'
    printf '\tlist - list users\n'
    printf '\thelp - display this help command\n'
}

add_user() {
    echo ""
}

del_user() {
    echo ""
}

list_users() {
    echo 'TODO: list LDAP'
}


[ "$(id -u)" -ne 0 ] && die 'This script should be run as root!'

case "$cmd" in
  add) [ $# -lt 3 ] && die 'Insufficient arguments!'
      if ! id -u "$user" >/dev/null 2>&1; then
          printf 'Creating user:\n'
          printf '\tUsername: %s\n' $user
          printf '\tEmail: %s\n' $email
          printf '\tSSH: %s\n\n' $ssh_pubkey
          if confirm 'Are those details correct?'; then
              add_user
          else
              echo 'Aborting.'
          fi
      else
          die "User '$user' already exists!"
      fi
      ;;
  del) [ $# -lt 2 ] && die 'Insufficient arguments!'
      if id -u "$user" >/dev/null 2>&1; then
          printf 'Deleting user: %s\n' $user
          if confirm 'Are you sure?'; then
              del_user
          else
              echo 'Aborting.'
          fi
      else
          die "User '$user' doesn't exist!"
      fi
      ;;
  list) list_users;;
  help|*) help;;
esac