#!/bin/sh
#
# linbo_auth
# thomas@linuxmuster.net
# 20250916
#

# get environment
source /usr/share/linbo/shell_functions
echo "### $timestamp $(basename "$0") ###"

usage(){
  echo
  echo "Authenticates linbo user."
  echo
  echo "Usage:"
  echo "  linbo_auth <password> | [help]"
  echo
  echo "For compatibility reasons legacy options are also accepted but not used:"
  echo "  linbo_auth <server> <user> <password>"
  echo
  exit 1
}

# print help
[ -z "$1" -o "$1" = "help" ] && usage

# last parameter is password in any case
export RSYNC_PASSWORD="$(echo "$@" | awk '{print $NF}')"

if [ -s /etc/linbo_pwhash -a -s /etc/linbo_salt ]; then
  echo "Using local authentication ..."
  linbo_pwhash="$(cat /etc/linbo_pwhash)"
  linbo_salt="$(cat /etc/linbo_salt)"
  given_pwhash="$(echo "$RSYNC_PASSWORD" | LANG=C argon2 "$linbo_salt" -t 1000 | grep ^Hash | awk '{print $2}')"
  if [ "$given_pwhash" = "$linbo_pwhash" ]; then
    msg="Password matches."; RC=0
    # temporary workaround for password
    echo -n "$RSYNC_PASSWORD" > /tmp/linbo.passwd
  else
    msg="Password does not match!"; RC=1
  fi
else
  msg="No password hash available!"; RC=2
fi

echo "$msg"

exit "$RC"
