#!/bin/bash

###
# @author Markus Kusserow <markus.kusserow@bfr.bund.de>
# @version 2023.01.05.01
# @copyright 2023 BfR
###

### DATA ###

_HOME_=/root
_SSH_DIR_="${_HOME_}/.ssh"
_SSH_AUTHORIZE_KEYS_FILE_="${_SSH_DIR_}/authorized_keys"
_CMDLINE_=($(cat /proc/cmdline))
_ANSIBLE_USER_='ansible'
_ANSIBLE_HOME_="/home/${_ANSIBLE_USER_}"


### FUNCTIONS ###

# download file
# @param string file
# @param string src
download_file () {
  local _FILE_=$1
  local _SRC_=$2

  if [ "${_SRC_:0:4}" = 'http' ] ; then
    wget --no-proxy -qO "${_FILE_}" "${_SRC_}"
    return $?
  else
    cp "${_SRC_}" "${_FILE_}"
    return $?
  fi
}

### PROCESS ###

# ensures that new files can only be accessed
# by root unless otherwise specified
umask 0077

# ensures that root's home directory can only be accessed by root
chmod 0700 "${_HOME_}"

# ensures that the current directory is root's home directory
cd "${_HOME_}"

# create root's ssh config directory
if [ ! -d "${_SSH_DIR_}" ] ; then
  mkdir "${_SSH_DIR_}"
fi

_BASE_URL_=
_SSH_AUTHORIZE_KEYS_URL_=

# get base url rom kernel boot parameters
for _KV_ in ${_CMDLINE_[*]} ; do
  # split key and value
  _KV_=(${_KV_/=/ })
  # if key is file
  if [ "${_KV_[0]}" = 'file' -a ! -z "${_KV_[1]}" ] ; then
    # set base url
    _BASE_URL_="/root/${_KV_[1]#/*/}"
    _BASE_URL_="${_BASE_URL_%/*}"
    break
  fi
  # if key is url
  if [ "${_KV_[0]}" = 'url' -a ! -z "${_KV_[1]}" ] ; then
    # set base url
    _BASE_URL_="${_KV_[1]%/*}"
    break
  fi
done

# if base url is not empty
if [ ! -z "${_BASE_URL_}" ] ; then
  _SSH_AUTHORIZE_KEYS_URL_="${_BASE_URL_}/authorized_keys"
fi

# save install date time
date +%Y-%m-%d\ %H:%M:%S\ %Z\ %s >> .install_time

# configure ssh service
# - enable root login by key only
# - disable password authentication
cat > /etc/ssh/sshd_config.d/000_local.conf <<EOF
PermitRootLogin prohibit-password
PasswordAuthentication no
EOF

# check if eth0 exists in default interfaces config
grep eth0 '/etc/network/interfaces' >/dev/null 2>&1

# if eth0 is not found in default interfaces config
if [ $? -ne 0 ] ; then
# create config for eth0
cat > /etc/network/interfaces.d/000-eth0 <<EOF
# The primary network interface
allow-hotplug eth0
iface eth0 inet dhcp
EOF

fi

# download authorized keys file
download_file "${_SSH_AUTHORIZE_KEYS_FILE_}" "${_SSH_AUTHORIZE_KEYS_URL_}"

# if ansible home exists, assume ansible user exists
if [ -d "${_ANSIBLE_HOME_}" ] ; then
  # create ssh authorized_keys file with correct permissions
  _NEW_DIR_="${_ANSIBLE_HOME_}/.ssh"
  _NEW_FILE_="${_NEW_DIR_}/authorized_keys"

  if [ ! -d "${_NEW_DIR_}" ] ; then
    mkdir -m 0700 "${_NEW_DIR_}"
  fi

  touch "${_NEW_FILE_}"
  chmod 0600 "${_NEW_FILE_}"
  chown "${_ANSIBLE_USER_}":"${_ANSIBLE_GROUP_}" -R "${_NEW_DIR_}"

  cat "${_SSH_AUTHORIZE_KEYS_FILE_}" > "${_NEW_FILE_}"
fi

