#!/bin/bash
#
# Script Name: pwrand
# Description: Generates a password with the pseudorandom number generator
# /dev/urandom.
#
# Copyright (C) 2020 by Intevation GmbH
# Author: Benedikt Tuchen <benedikt@intevation.de>
#
# This program is free software under the GNU GPL (>=v2)
# -------------------------------------------------------------------

# Default values
CHARS='A-Za-z0-9'
PW_LENGTH=12
NUM_PW=1

# Check if $1 ARG is a number
numbercheck='^[0-9]+$'

usage() {
  echo "Usage: pwrand [ OPTIONS ] [ pw_length ] [ num_pw ]"
  echo
  echo "-h or --help"
  echo "     Print this help message"
  echo "-s or --special"
  echo "     Generate passwords with special characters"
}

if [[ "$1" = "-h" ]] || [[ "$1" = "--help" ]]
then
  usage
  exit 0
fi

if [[ "$1" = "-s" ]] || [[ "$1" = "--special" ]]
then
  CHARS='A-Za-z0-9@#%*=-'
  shift
fi

if [[ $# -ne 0 ]] && [[ $1 =~ $numbercheck ]]
then
  PW_LENGTH=$1
  shift
fi

if [[ $# -ne 0 ]] && [[ $1 =~ $numbercheck ]]
then
  NUM_PW=$1
  shift
fi

if [ $# -ne 0 ]
then
  usage >&2
  exit 1
fi

for (( i = 0; i < $NUM_PW; i++ ))
do
  tr -dc $CHARS < /dev/urandom | tr -d B8G6I1l0OQDS5Z2 | head -c $PW_LENGTH
  echo
done
