#!/bin/bash

. /usr/lib/lib-fliwi/ymc-common.sh || exit 1

fliwi_tool_name="fliwi-update-remote-access"


system_users=$(fliwi-get-my-access-groups --show-access-as-system-user | grep -v -E -e '^root$' | sort -V -u)

for system_user in root $system_users
do
  admins=$(fliwi-get-my-access-groups --show-access-as-system-user --show-members | grep -E -e "^$system_user " | cut -d ' ' -f 2 | sed -r 's/,/ /g')
  if [ "$system_user" == "root" ]; then
    admins="$admins $(fliwi-get-my-human-admins)"
    home='/root'
  else
    home=$(cat /etc/passwd | grep -E -e "^$system_user:" | cut -d ':' -f 6)
  fi

  admins=$(echo $admins | sed -r 's/[[:space:]]+/\n/g' | sort -V -u)

  if [ "$admins" == '' ]; then
    echo "WARNING: No admins found for this host for user '$system_user' - skipping" 1>&2
    continue
  fi

  if [ ! -d "$home/.ssh" ]; then
    mkdir -p $home/.ssh
    chmod 700 $home/.ssh
    chown $system_user $home/.ssh
  fi

  if [ ! -f "$home/.ssh/authorized_keys" ]; then
    su $system_user -c "touch $home/.ssh/authorized_keys"
    su $system_user -c "chmod 644 $home/.ssh/authorized_keys"
  fi

  ### Wash out possibly old entries added by this tool in $home/.ssh/authorized_keys
  fliwi_modify_file_remove_added_block $home/.ssh/authorized_keys "Added by $fliwi_tool_name"

  ### Add new entries in $home/.ssh/authorized_keys
  fliwi_modify_file_add_block_start $home/.ssh/authorized_keys "Added by $fliwi_tool_name"
  for admin in $admins
  do
    if [ -f "/etc/fliwi/global/access/admins/$admin" ] && [ -r "/etc/fliwi/global/access/admins/$admin" ]; then
      echo "# Admin: $admin" >> $home/.ssh/authorized_keys
      cat /etc/fliwi/global/access/admins/$admin >> $home/.ssh/authorized_keys
      echo "" >> $home/.ssh/authorized_keys
    else
      echo "WARNING: Admin '$admin' configured for user '$system_user', but no public ssh key found at '/etc/fliwi/global/access/admins/$admin'" 1>&2
    fi
  done
  fliwi_modify_file_add_block_end $home/.ssh/authorized_keys "Added by $fliwi_tool_name"
done

