#!/usr/bin/env bash

script_name="$(basename $(realpath $0))"
working_dir="$(dirname $(realpath $0))"

conf_file="${working_dir}/conf/${script_name%%.*}.conf"

LOCK_DIR="/tmp/$(basename $0).$$.LOCK"
log_file="${LOCK_DIR}/${script_name%%.*}.log"

# ----------
# Variables
# ----------

password_file="/tmp/passwd"

# ----------
# Functions
# ----------

trim() {
    local var="$*"
    var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
    var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
    echo -n "$var"
}



while IFS=' ' read _user _pw _salt || [[ -n $_line ]] ; do

   user=$_user
   passwd=$_pw
   salt=$_salt

   # ignore empty lines
   #
   [[ -z "$(trim $user)" ]] && continue
   [[ "$(trim $user)" =~ ^# ]] && continue

   [[ -z $salt ]] && salt=$(tr -cd 'a-zA-Z0-9' < /dev/urandom | head -c 8)

   passwd_hash="$(mkpasswd -m SHA-512 $passwd $salt)"

   echo ""
   echo "password: '${passwd}' - salt: $ $salt"
   echo "${user}:$passwd_hash"
   
done < "$password_file"


echo ""
exit 0
