#!/bin/bash

display_fingerprints() {
  if [ -d /etc/tinyssh/sshkeydir ]; then
      tinysshd-printkey /etc/tinyssh/sshkeydir
  fi
}

generate_keys() {
  if [ ! -d /etc/tinyssh/sshkeydir ]; then
      tinysshd-makekey /etc/tinyssh/sshkeydir
      if [ $? -eq 0 ]; then
          echo "Generated tinyssh keys..."
          return 0
      fi
  fi
  return 1
}

copy_openssh_keys() {
  local osshed25519="/etc/ssh/ssh_host_ed25519_key"

  local destdir="/etc/tinyssh/sshkeydir"

  local return_code=1

  if [ ! -d $destdir -a -x /usr/bin/tinyssh-convert ]; then
      mkdir $destdir
  fi
  
  if [ -s "$osshed25519" -a ! -s $destdir/.ed25519.sk -a ! -s $destdir/ed25519.pk -a -x /usr/bin/tinyssh-convert ]; then
      tinyssh-convert -f $osshed25519 -d $destdir
      if [ $? -eq 0 ]; then
          return_code=0
      fi
  fi

  if [ $return_code -eq 0 ]; then
      echo "Converted keys from OpenSSH..."
  fi

  return $return_code
}

create_systemd_customdep () {
    add_dir "/etc/systemd/system/tinyssh@22.socket.d"
    cat << CUSTOMEOF > "${BUILDROOT}/etc/systemd/system/tinyssh@22.socket.d/cryptsetup-dep.conf"
[Unit]
Before=
Before=cryptsetup.target
CUSTOMEOF
}

build ()
{
  #
  # Begin real processing
  #

  # Are we even needed?
  if [ ! -r "/etc/tinyssh/root_key" -o ! -s "/etc/tinyssh/root_key" ]; then
    echo "There is no root key in /etc/tinyssh/root_key existent; exit"
    return 0
  fi

  # if TMPDIR is set leave it alone otherwise set
  [ -z $TMPDIR ] && TMPDIR='/tmp/mkinitcpio-tinyssh'

  # check if TMPDIR exsists if not make it
  [ -d $TMPDIR ] || mkdir -p $TMPDIR

  umask 0022

  copy_openssh_keys || generate_keys
  display_fingerprints

  #systemd enabled
  declare -F add_systemd_unit > /dev/null 2>&1
  if [ $? -eq 0 ]; then
      add_systemd_unit "tinysshgenkeys.service"
      add_systemd_unit "tinyssh@.socket"
      add_systemd_unit "tinyssh@.service"
      systemctl --root "$BUILDROOT" enable tinyssh@22.socket
      create_systemd_customdep
  #base enabled
  else
      add_checked_modules "/drivers/net/"
      add_binary "rm"
      add_binary "killall"
      add_binary "tinysshd"
      add_file "/lib/libnss_files.so.2"
      add_runscript
  fi

  #both
  add_dir "/root/.ssh"
  cat /etc/tinyssh/root_key > "${BUILDROOT}"/root/.ssh/authorized_keys

  #necessary for tinyssh private keys
  shopt -s dotglob
  add_full_dir "/etc/tinyssh"
  shopt -u dotglob

}

help ()
{
    cat<<HELPEOF
This hook is meant to be used in conjunction with mkinitcpio-netconf and/or
mkinitcpio-ppp. It DOES NOT provide any default shell. It will only install
and start tinyssh on early userspace. In the package mkinitcpio-utils you
will find hooks and shells for remote unlocking a luks root partition,
among others.
HELPEOF
}
