#!/bin/sh

<< MIT-LICENSE
Copyright (c) 2023 Jianjun Liu<jianjunliu@126.com> https://www.pkglinux.top

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
MIT-LICENSE

echo "Mounting root devices read-only ..."
/bin/mount -n -o remount,ro /
if mountpoint -q /bin; then
    /bin/mount -n -o remount,ro /bin
fi; if mountpoint -q /etc; then
    /bin/mount -n -o remount,ro /etc
fi; if mountpoint -q /lib; then
    /bin/mount -n -o remount,ro /lib
fi; if mountpoint -q /lib32; then
    /bin/mount -n -o remount,ro /lib32
fi; if mountpoint -q /libx32; then
    /bin/mount -n -o remount,ro /libx32
fi; if mountpoint -q /lib64; then
    /bin/mount -n -o remount,ro /lib64
fi; if mountpoint -q /sbin; then
    /bin/mount -n -o remount,ro /sbin
fi; if mountpoint -q /usr; then
    /bin/mount -n -o remount,ro /usr
fi

echo "Making /dev/pts for pseudo terminal slaves ..."
mkdir -p /dev/pts

# These mount points already exist and are moved automatically when using an initramfs and switch_root
echo "Mounting temporary filesystems ..."
mountpoint -q /proc || mount -n -t proc     proc     /proc
mountpoint -q /sys  || mount -n -t sysfs    sysfs    /sys
mountpoint -q /dev  || mount -n -t devtmpfs devtmpfs /dev
mountpoint -q /run  || mount -n -t tmpfs    tmpfs    /run
mountpoint -q /tmp  || mount -n -t tmpfs    tmpfs    /tmp

# This is needed since eudev (around version 3.0) because it no longer creates static devices nodes, like /dev/fuse and /dev/net/tun
echo "Creating static device nodes ..."
/bin/kmod static-nodes --format=tmpfiles | \
while read type name mode uid gid age arg; do
  [ -e $name ] && continue
  case "$type" in
    c|b|c!|b!) mknod -m $mode $name $type $(echo $arg | sed 's/:/ /') ;;
    d|d!) mkdir $name ;;
    *) echo "unparseable line ($type $name $mode $uid $gid $age $arg)" >&2 ;;
  esac
done

echo "Stopping existing udevd daemon ..."
udevadm control --exit
echo "Starting udevd as a daemon ..."
udevd --daemon
# Enable trigger event to autoload modules for devices
echo "Triggering with udevadm ..."
udevadm trigger --action=add --type=subsystems
udevadm trigger --action=add --type=devices
echo "Settling with udevadm ..."
udevadm settle

if [ -e /etc/crypttab ]; then
  echo "Found /etc/crypttab ..."
  grep -v '^#' /etc/crypttab | grep -v '^[[:space:]]*$' | \
  while read tgt src pw opts ; do
    # If the source does not exist ignore it. Options are also ignored
    if ! [ -e "$src" ]; then
      continue
    fi

    # If the target already exists, ignore it.
    if [[ -e /dev/mapper/"$tgt" ]]; then
      echo "Crypt device $tgt already exists, not trying to open it"
      continue
    fi

    if [[ $tgt = "swap" ]]; then
      OVERWRITE=0
      # Swap device, hardcoded options, only mount when blkid cannot find a type
      blkid $src | grep TYPE >/dev/null
      (( $? == 1 )) && OVERWRITE=1
      if [[ $OVERWRITE = 1 ]]; then
        # Swap cipher hardcoded for now
        cryptsetup --key-file /dev/urandom --cipher aes-cbc-essiv:sha256 open --type plain "$src" "$tgt"
        mkswap /dev/mapper/"$tgt"
      else
        echo "Warning! /etc/crypttab lists $src as a swap target but this partition is not a swap partition, mkswap it first if you are sure."
      fi
    else
      echo "Attempting to open encrypted device $tgt ..."
      cryptsetup --key-file=$pw luksOpen "$src" "$tgt"
    fi
  done
fi

echo "Setting up swap partitions ..."
/sbin/swapon -a

/sbin/fsck -A -a -C
if [ $? -gt 1 ]; then
   echo -e "\nFilesystem errors detected. You can probably correct this"
   echo "problem by running e2fsck manually (eg. with the -v and -y options)."
   echo -e "After you logout, the system will reboot.\n"
   PS1="(Repair filesystem)# "
   export PS1
   /sbin/sulogin
   /bin/umount -a -r
   /sbin/reboot -f
fi

echo "Remounting root devices read-write ..."
/bin/mount -n -v -o remount,rw /
if mountpoint -q /bin; then
    /bin/mount -n -v -o remount,rw /bin
fi; if mountpoint -q /etc; then
    /bin/mount -n -v -o remount,rw /etc
fi; if mountpoint -q /lib; then
    /bin/mount -n -v -o remount,rw /lib
fi; if mountpoint -q /lib32; then
    /bin/mount -n -v -o remount,rw /lib32
fi; if mountpoint -q /libx32; then
    /bin/mount -n -v -o remount,rw /libx32
fi; if mountpoint -q /lib64; then
    /bin/mount -n -v -o remount,rw /lib64
fi; if mountpoint -q /sbin; then
    /bin/mount -n -v -o remount,rw /sbin
fi; if mountpoint -q /usr; then
    /bin/mount -n -v -o remount,rw /usr
fi

echo "Setting up swap files ..."
/sbin/swapon -a

echo "Initializing kernel random number generator ..."
if [ -f /var/tmp/random-seed ]; then
   /bin/cat /var/tmp/random-seed >/dev/urandom
fi
/bin/dd if=/dev/urandom of=/var/tmp/random-seed count=1 &>/dev/null

echo "Setting up utmp ..."
touch /var/run/utmp
if grep -q '^utmp:' /etc/group; then
  echo "Found utmp in /etc/group"
  chmod 664 /var/run/utmp
  chgrp utmp /var/run/utmp
fi

echo "Creating virtual filesystems ..."
mkdir -p /run/lock /run/shm
chmod 1777 /run/shm /run/lock
ln -sfn /run/shm /dev/shm

echo "Setting up the loopback interface ..."
#modprobe loop
#ip addr flush
ip addr add 127.0.0.1/8 label lo dev lo
ip link set lo up
modprobe loop

echo "Setting up /etc/hostname ..."
/bin/hostname `cat /etc/hostname`

# Run in the background because this command can take over a second
echo "Setting system time from hardware clock ..."
/sbin/hwclock --hctosys &

echo "Starting syslogd ...."
/sbin/syslogd
echo "Starting klogd ...."
/sbin/klogd -c3

# Regenerate the modules.dep file if any modules are newer than it
echo "Updating /lib/modules/kernel-version/modules.dep.* if neccessary  ..."
/sbin/depmod -A

echo "Mount remaining filesystems from /etc/fstab ..."
mount -a

if [ -f /etc/sysctl.conf ]; then
  echo "Found /etc/sysctl.conf"
  echo "Setting kernel runtime parameters ..."
  sysctl -q -p
fi


yes1() {
    [ "$1" = "1" ] || [ "$1" = "yes" ] || [ "$1" = "true" ]
}

# Probably no /etc/sysconfig/console at all
[ -r /etc/sysconfig/console ] && . /etc/sysconfig/console

if [ -n "${KEYMAP}" ] || [ -n "${KEYMAP_CORRECTIONS}" ] || 
   [ -n "${FONT}"   ] || [ -n "${LEGACY_CHARSET}"     ] || yes1 ${UNICODE}; then 
    echo "Setting up Linux console ..."

    # Figure out if a framebuffer console is used
    [ -d /sys/class/graphics/fb0 ] && USE_FB=1 || USE_FB=0

    # Figure out the command to set the console into the desired mode
    yes1 "${UNICODE}" && MODE_COMMAND="echo -en '\033%G' && kbd_mode -u" ||
    MODE_COMMAND="echo -en '\033%@\033(K' && kbd_mode -a"

    # On framebuffer consoles, font has to be set for each vt in
    # UTF-8 mode. This doesn't hurt in non-UTF-8 mode also.

    ! yes1 "${USE_FB}" || [ -z "${FONT}" ] ||
    MODE_COMMAND="${MODE_COMMAND} && setfont ${FONT}"

    # Apply that command to all consoles mentioned in
    # /etc/inittab. Important: in the UTF-8 mode this should
    # happen before setfont, otherwise a kernel bug will
    # show up and the unicode map of the font will not be
    # used.

    for TTY in `grep '^[^#].*respawn:/sbin/agetty' /etc/inittab | grep -o '\btty[[:digit:]]*\b'`
    do
         openvt -f -w -c ${TTY#tty} -- /bin/sh -c "${MODE_COMMAND}"
    done

    # Set the font (if not already set above) and the keymap
    [ "${USE_FB}" == "1" ] || [ -z "${FONT}" ] || setfont ${FONT}
    [ -z "${KEYMAP}" ] || loadkeys ${KEYMAP} >/dev/null 2>&1
    [ -z "${KEYMAP_CORRECTIONS}" ] || loadkeys ${KEYMAP_CORRECTIONS} >/dev/null 2>&1

    # Convert the keymap from $LEGACY_CHARSET to UTF-8
    [ -z "$LEGACY_CHARSET" ] || dumpkeys -c "$LEGACY_CHARSET" | loadkeys -u >/dev/null 2>&1
fi

# Create symbolic link /pkglinux.sfs
sfs=""
sfs=$(cat /proc/cmdline| tr ' ' '\n' | grep sfs= | cut -d'=' -f2)
[ -n "$sfs" ] && [ -f "/sfs.root/$sfs/pkglinux.sfs" ] && ln -snvf /sfs.root/$sfs/pkglinux.sfs /pkglinux.sfs
[ -n "$sfs" ] && [ -f "/$sfs/pkglinux.sfs" ] && ln -snvf /$sfs/pkglinux.sfs /pkglinux.sfs

# Load a new SELinux policy into the kernel
echo "Load SELinux config and policy ..."
security="selinux"
selinux="1"
security=$(cat /proc/cmdline| tr ' ' '\n' | grep security= | cut -d'=' -f2)
if [ "$security" == "selinux" ]; then
  selinux=$(cat /proc/cmdline| tr ' ' '\n' | grep selinux= | cut -d'=' -f2)
  if [ "$selinux" == "1" ]; then
    SELINUX="disabled"
    [ -e "/etc/selinux/config" ] && . /etc/selinux/config && \
    [ "$SELINUX" != "disabled" ] && load_policy -i && \
    [ -e /.autorelabel ] && restorecon -R /
  fi
fi

udevadm control --reload-rules && udevadm trigger

/etc/rc.d/rc ${@}
