#!/bin/sh
PARAMS=$(</proc/cmdline)
# find vfloppy device (based on IPA code)
VMEDIA_DEVICE=$(find /dev/disk/by-label -iname ir-vfd-dev)
# read params from vmedia and prepend them to params from kernel cmdline
if [[ -b "$VMEDIA_DEVICE" ]]; then
  VMEDIA_MOUNT=$(mktemp -d)
  if mount -o loop $VMEDIA_DEVICE $VMEDIA_MOUNT; then
    # parameters.txt has one param per line, reformat to match cmdline
    VMEDIA_PARAMS=$(cat $VMEDIA_MOUNT/parameters.txt | tr '\n' ' ')
    umount $VMEDIA_MOUNT
    PARAMS="$VMEDIA_PARAMS $PARAMS"
  fi
  rmdir $VMEDIA_MOUNT
fi

# resize /tmp
if [[ $PARAMS =~ suse.tmpsize=([^ ]+) ]]; then
  echo "Resizing /tmp to ${BASH_REMATCH[1]}..."
  mount -o remount,size=${BASH_REMATCH[1]} /tmp
fi
# deploy authorized sshkey from kernel command line
if [[ $PARAMS =~ sshkey=\"([^\"]+)\" ]]; then
  echo "Adding authorized SSH key..."
  (umask 077 ; mkdir -p /root/.ssh)
  echo "${BASH_REMATCH[1]}" >> /root/.ssh/authorized_keys
fi
# Inject certs
if [[ $PARAMS =~ tls.enabled=(true|True) ]]; then
  cp /etc/ironic-python-agent.d/ca-certs/* /etc/pki/trust/anchors/
  cp /etc/ironic-python-agent.d/ca-certs/* /usr/share/pki/trust/anchors/
  update-ca-certificates
fi
# autologin root on given console (default tty1) if suse.autologin or coreos.autologin is enabled
if [[ $PARAMS =~ (suse|coreos)\.autologin=?([^ ]*) ]]; then
  tty="${BASH_REMATCH[2]:-tty1}"
  echo "Enabling autologin on $tty..."
  systemctl stop getty@$tty
  systemctl disable getty@$tty
  systemctl start autologin@$tty
fi

# Append to /etc/hosts
# hosts.append=1.2.3.4_foo,4.5.6.7_foo2
if [[ $PARAMS =~ hosts.append=([^ ]+) ]]; then
  HOSTS=${BASH_REMATCH[1]}
  echo "Appending to hosts ${HOSTS}..."
  for h in ${HOSTS/,/ }; do
    echo "${h/_/ }" >> /etc/hosts
  done
  cat /etc/hosts
fi
