#! /bin/sh

# Ensure some directory trees are completely writable.
#
# ... but /etc/systemd will be treated specially (see below): move it aside
# for now.
#
mv /etc/systemd /etc_systemd
for i in /etc /media /root /run /var ; do
  cp -aL $i ${i}_tmp
  rm -rf $i
  mv ${i}_tmp $i
  ln -snf /proc/self/mounts /etc/mtab
done
mv /etc_systemd /etc/systemd

# /etc/systemd: keep symlinks instead of files (bsc #1044791)
#
# In particular, this keeps symlinks to files except for config files (*.conf)
# and resolves links to directories.
#
for i in /etc/systemd/* /etc/systemd/*/* ; do
  if [ -L $i ] ; then
    if [ -d $i ] ; then
      mv $i ${i}_tmp
      cp -a ${i}_tmp/ $i
      rm -f ${i}_tmp
    elif [ -f $i ] ; then
      case $i in
        *.conf) cp -L $i ${i}_tmp ; mv ${i}_tmp $i ;;
      esac
    fi
  fi
done

if [ -f /mounts/initrd/etc/suse-blinux.conf ] ; then
  grep -q '^brlname=none' /mounts/initrd/etc/suse-blinux.conf || {
    cp /mounts/initrd/etc/suse-blinux.conf /etc
    systemctl enable brld
    systemctl enable sbl
  }
fi

if [ -e /usr/lib/systemd/system/sshd.service -a "$SSH" = 1 ] ; then
  cp -f /usr/lib/systemd/system/sshd.service /etc/systemd/system
  ln -s ../sshd.service /etc/systemd/system/multi-user.target.wants
fi

if [ -n "$SSHPASSWORD" ] ; then
  echo "root:$SSHPASSWORD" | chpasswd
else
  echo "root:$SSHPASSWORDENC" | chpasswd -e
fi

# keep some initrd config files for rescue system
cd /mounts/initrd
for i in \
  etc/modprobe.d/{blacklist,noload,99-unsupported-modules}.conf etc/resolv.conf \
  etc/sysconfig/network/* root/.ssh etc/nvme \
  ; do
  [ -f "$i" ] && cp -f "$i" "/$i"
  [ -d "$i" ] && cp -fr --parents "$i" /
done
cd /

# create machine id
a=`dd if=/dev/urandom bs=1 count=10 2>/dev/null | md5sum` ; echo ${a%% *} >/etc/machine-id

# preserve hostname
hostname >/etc/hostname

# driver update: add files to inst-sys
if [ -d /mounts/initrd/update ] ; then
  cp -r /mounts/initrd/update /
  for i in /update/[0-9]*/inst-sys ; do
    [ -d "$i" ] && /mounts/initrd/sbin/adddir "$i" /
  done
fi

# ensure all base modules are loaded - they will not be available in the
# rescue system (bsc#1183388)
for i in $(cat /mounts/initrd/.base_modules) ; do
  modprobe -q -d /mounts/initrd $i
done

if [ "$startshell" = 1 ] ; then
  mount -t proc proc /proc
  echo "exit shell to continue startup process..."
  bash >/dev/console 2>&1
  umount /proc
fi

rm -f /mounts/initrd/{*,.*}
rmdir /mounts/initrd/* 2>/dev/null
rm -rf /mounts/initrd/{bin,download,etc,lbin,lib,modules,oldroot,root,sbin,scripts,tmp,usr,var}
rm -f /mounts/initrd/parts/* 2>/dev/null
