# default keyboard and language
#keyboard 'us'
#lang en_US.UTF-8

# We do not want SELinux
selinux --disabled

# Services to activate
services --disabled=lm_sensors

# Default root pass, will be changed in post-install process anyway
rootpw --lock
user --name=installer --uid=9999

# Accept EULA
eula --agreed

# don't install X
skipx

# Partitioning from pre section
%include /tmp/part-include

# Disable kdump
%addon com_redhat_kdump --disable
%end

# Install type and location information
%include /tmp/install_include

# Packages to install
%packages --nocore
%include /tmp/packages-include
%end

# Modular
%include /tmp/modular-include

# Partitioning in pre-install
%pre --interpreter=/bin/bash --log=/var/log/sme-partitioning.log

# Default values
DEFAULT_INSTALL="ISO"
DEFAULT_CONTRIBS=""
DEFAULT_ADDONS=""
DEFAULT_FILESYSTEM="xfs"
DEFAULT_USE_LVM="yes"
DEFAULT_USE_RAID="yes"

# Read command line arguments
if grep sme.netinstall "/proc/cmdline" ; then DEFAULT_INSTALL="netinstall" ; fi
if grep sme.contribs "/proc/cmdline" ; then DEFAULT_CONTRIBS=true ; fi
if grep sme.addons "/proc/cmdline" ; then DEFAULT_ADDONS=true ; fi
if grep nolvm "/proc/cmdline" ; then NOLVM=true ; DEFAULT_USE_LVM="no" ; fi
if grep noraid "/proc/cmdline" ; then NORAID=true ; DEFAULT_USE_RAID="no" ; fi
if grep noxfs "/proc/cmdline" ; then FSTYPE="ext4" ; else FSTYPE="xfs" ; fi 
echo "Command line arguments:"
cat /proc/cmdline

echo "[$(date '+%Y-%m-%d %H:%M:%S')] === Starting Install Configuration ==="

# create the common part of the packages section
cat > /tmp/packages-include <<EOF
@^smeserver
bash
chkconfig
glibc-all-langpacks
initscripts
kernel
kernel-modules
chrony
kexec-tools
-cockpit
EOF

# add the common modules
cat > /tmp/modular-include <<EOF
module --name=httpd --stream=2.4
module --name=php --stream=remi-8.4
module --name=python36 --stream=3.6
module --name=perl-DBD-MySQL --stream=4.046
module --name=perl-DBD-SQLite --stream=1.58
module --name=perl-DBI --stream=1.641
module --name=perl-IO-Socket-SSL --stream=2.066
module --name=perl-libwww-perl --stream=6.34
module --name=squid --stream=4
module --name=container-tools --stream=rhel8
module --name=freeradius --stream=3.0
module --name=nginx --stream=1.14
EOF

# do the source stuff
if [[ $DEFAULT_INSTALL == "netinstall" ]] ; then 
    cat > /tmp/install_include <<EOF
# Base URL for netinstall
url --mirrorlist https://mirrorlist.koozali.org/mirrorlist/smeos-11-x86_64
EOF
else # default to an ISO install (may expand in the future)
    cat > /tmp/install_include <<EOF
# Install from the cdrom - use harddrive as cdrom option fails
harddrive --partition=/dev/disk/by-label/SMESERVER --dir=/
EOF
fi

# start the network if we are doing a network install OR we have selected to install contribs
if [[ $DEFAULT_INSTALL == "netinstall" || $DEFAULT_CONTRIBS || $DEFAULT_ADDONS ]] ; then 
    cat >> /tmp/install_include <<EOF
# Start network
network --bootproto=dhcp --device=link --activate
EOF
fi

# load the smecontribs repo
if [[ $DEFAULT_CONTRIBS ]] ; then
    cat >> /tmp/install_include <<EOF
# smecontribs repo and other supporting ones, for selecting additional software
# using baseurl as mirrorlist is flaky
repo --name=smecontribs --baseurl=https://distro.ibiblio.org/smeserver/releases/testing/11/smecontribs/x86_64
EOF
fi

# load the smeaddons repo
if [[ $DEFAULT_ADDONS ]] ; then
    cat >> /tmp/install_include <<EOF
# smeaddons repo, for selecting additional software
# using baseurl as mirrorlist is flaky
repo --name=smeaddons --baseurl=https://distro.ibiblio.org/smeserver/releases/testing/11/smeaddons/x86_64
EOF
fi

# add the additional repos required by smecontribs and smeaddons 
if [[ $DEFAULT_CONTRIBS || $DEFAULT_ADDONS ]] ; then
    cat >> /tmp/install_include <<EOF
repo --name=epel --baseurl=https://download.fedoraproject.org/pub/epel/8/Everything/x86_64
repo --name=powertools --baseurl=https://dl.rockylinux.org/pub/rocky/8/PowerTools/x86_64/os
repo --name=remi-modular --baseurl=https://rpms.remirepo.net/enterprise/8/modular/x86_64/
EOF
# add epel-release because we have included epel (which requires powertools)
    cat >> /tmp/packages-include <<EOF
epel-release
EOF
# add modules from powertools, epel and remi
    cat >> /tmp/modular-include <<EOF
# additional module settings for smecontribs
module --name=virt --stream=rhel
module --name=redis --stream=remi-7.2
EOF
fi

echo "[$(date '+%Y-%m-%d %H:%M:%S')] === Starting Storage Configuration ==="
    
# Get system information
if ! RAM_MB=$(free -m | awk '/^Mem:/{print $2}'); then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Error: Could not determine RAM"
    exit 1
fi
    
# create kickstart disk partitioning
# Minimum size of hard drive needed specified in MB
MINSIZE=5000

# Number of detected drives and first disk size
NDEV=0
BASESIZE=0
SIZEDIFF=0

# Loop through block devices, keep those over MINSIZE and ensure additional drives for RAID are within 100MB of the first
for DEV in $(lsblk -nl | grep disk | cut -d' ' -f1) ; do
  echo "DEV:$DEV"
  if [ -d /sys/block/$DEV ] ; then
    REMOVABLE=`cat /sys/block/$DEV/removable`
    if [[ $REMOVABLE == 0 ]] ; then
      SIZE=`cat /sys/block/$DEV/size`
      MB=$(($SIZE/2**11))
      if [ $MB -gt $MINSIZE ] ; then
        if [ $NDEV == 0 ] ; then
          echo "First drive found: $DEV with size $MB MB"
          DRIVES[$NDEV]=$DEV
          BASESIZE=$MB
          ((NDEV++))
        else
          SIZEDIFF=$(($MB-$BASESIZE))
          if [ $SIZEDIFF -gt 100 ] || [ $SIZEDIFF -lt -100 ] ; then
            echo "Drive found but size of $MB MB doesn't match $BASESIZE MB - ignoring"
          else
            echo "Additional drive found: $DEV with size $MB MB"
            DRIVES[$NDEV]=$DEV
            ((NDEV++))
          fi
        fi
      fi
    fi
  fi
done
echo "Total disks found: $NDEV"

# Calculate recommended swap size for RAID + nolvm case
if [ -d /sys/firmware/efi ] ; then
  DISKSPARE=$(($BASESIZE-200-500-3000))
else
  DISKSPARE=$(($BASESIZE-1-500-3000))
fi
MEMSIZE=$(awk '/^MemTotal:/{print $2}' /proc/meminfo)
MEMSIZEMB=$(($MEMSIZE/2**10))

if [ $MEMSIZEMB -lt 2000 ] ; then
  SWAP_SIZE=$((2*$MEMSIZEMB))
elif [ $MEMSIZEMB -lt 8000 ] ; then
  SWAP_SIZE=$MEMSIZEMB
else
  SWAP_SIZE=8000
fi
if [ $SWAP_SIZE -gt $DISKSPARE ] ; then SWAP_SIZE=$DISKSPARE ; fi

# Declare useful variables
printf -v DRIVE_LIST ",%s" "${DRIVES[@]}"
if [ $NORAID ] ; then
  DRIVE_LIST=${DRIVES[0]}
else
  DRIVE_LIST=${DRIVE_LIST:1}
fi

echo "Final drive list: $DRIVE_LIST"
LEVEL=1
SPARE=0

# Error if detection has failed and fall back
if [ ${#DRIVES[@]} == 0 ] ; then
  echo "No drive suitable for installation found! Reverting to Anaconda defaults."

  cat > /tmp/part-include <<EOF
# Clear the Master Boot Record
zerombr

# Clear current partitions
clearpart --all  --initlabel

# Automatically create partitions using LVM
autopart --type=lvm --nohome
EOF

# Otherwise clear detected devices and set up bootloader
else
  cat > /tmp/part-include <<EOF
# Clear the Master Boot Record
zerombr

# Clear current partitions and install bootloader
clearpart --all --drives=$DRIVE_LIST --initlabel
ignoredisk --only-use=$DRIVE_LIST
bootloader --location=mbr --driveorder=$DRIVE_LIST
EOF

  # If single disk or noraid specific then set up partitioning without RAID
  # NOTE: From this point we're appending to part-include
  if [ ${#DRIVES[@]} == 1 ] || [ $NORAID ] ; then

    # Include the EFI or biosboot partition if necessary
    if [ -d /sys/firmware/efi ] ; then
      printf "part /boot/efi --fstype=efi --size=200 --ondisk=%s\n" "${DRIVES[0]}" >> /tmp/part-include
    elif [ $BASESIZE -gt 2048000 ] ; then
      printf "part biosboot --fstype=biosboot --size=1 --ondisk=%s\n" "${DRIVES[0]}" >> /tmp/part-include
    fi

    # Create boot partition
    printf "part /boot --fstype=%s --size=512  --label=BOOT --ondisk=%s\n" "$FSTYPE" "${DRIVES[0]}" >> /tmp/part-include

    # Default to LVM unless specified at command line
    if [ $NOLVM ] ; then
      cat >> /tmp/part-include <<EOF
part / --fstype=$FSTYPE --grow --size=3000 --label=ROOT --ondisk=${DRIVES[0]}
part swap --fstype=swap --recommended --label=SWAP --ondisk=${DRIVES[0]}
EOF
    else
      cat >> /tmp/part-include <<EOF
part pv.01 --size=4300 --grow --ondisk=${DRIVES[0]}
volgroup main pv.01
logvol / --fstype=$FSTYPE --name=root --vgname=main --grow --size=3000
logvol swap --fstype=swap --name=swap --vgname=main --recommended
EOF
    fi

  # Otherwise multiple disks - prepare for RAID
  else

    # Define EFI or biosboot and RAID partitions
    for i in "${!DRIVES[@]}"; do

      if [ -d /sys/firmware/efi ] ; then
        printf "part raid.%s0 --size=200 --ondisk=%s\n" "$i" "${DRIVES[$i]}" >> /tmp/part-include
      elif [ $BASESIZE -gt 2048000 ] ; then
        printf "part biosboot --fstype=biosboot --size=1 --ondisk=%s\n" "${DRIVES[$i]}" >> /tmp/part-include
      fi
      printf "part raid.%s1 --size=512 --ondisk=%s\n" "$i" "${DRIVES[$i]}" >> /tmp/part-include

      # Default to LVM unless specified
      if [ $NOLVM ] ; then
        printf "part raid.%s2 --size=3000 --grow --ondisk=%s\n" "$i" "${DRIVES[$i]}" >> /tmp/part-include
        printf "part raid.%s3 --size=%s --ondisk=%s\n" "$i" "$SWAP_SIZE" "${DRIVES[$i]}" >> /tmp/part-include
      else
        printf "part raid.%s2 --size=4300 --grow --ondisk=%s\n" "$i" "${DRIVES[$i]}" >> /tmp/part-include
      fi

    done

    # Compute RAID level
    # from https://wiki.contribs.org/Raid
    # 2 Drives - Software RAID 1
    # 3 Drives - Software RAID 1 + 1 Hot-spare
    # 4 Drives - Software RAID 6
    # 5+ Drives - Software RAID 6 + 1 Hot-spare

    if [ ${#DRIVES[@]} == 2 ] ; then
      RAID_LEVEL=1
      SPARE=0
    elif [ ${#DRIVES[@]} == 3 ] ; then
      RAID_LEVEL=1
      SPARE=1
    elif [ ${#DRIVES[@]} == 4 ] ; then
      RAID_LEVEL=6
      SPARE=0
    else
      RAID_LEVEL=6
      SPARE=1
    fi

    # Set up RAID devices
    printf -v EFIDEVS "raid.%s0 " "${!DRIVES[@]}"
    printf -v BOOTDEVS "raid.%s1 " "${!DRIVES[@]}"
    printf -v ROOTDEVS "raid.%s2 " "${!DRIVES[@]}"
    printf -v SWAPDEVS "raid.%s3 " "${!DRIVES[@]}"
    
    # Include the EFI partition if necessary
    if [ -d /sys/firmware/efi ] ; then
      printf "raid /boot/efi --fstype=efi --level=1 --spares=0 --device=md9 %s\n" "$EFIDEVS" >> /tmp/part-include
    fi

    # Boot partition
    printf "raid /boot --fstype=%s --level=1 --spares=0 --device=md0 %s\n" "$FSTYPE" "$BOOTDEVS" >> /tmp/part-include

    # Default to LVM unless specified
    if [ $NOLVM ] ; then
      cat >> /tmp/part-include <<EOF
raid / --fstype=$FSTYPE --level=$RAID_LEVEL --spares=$SPARE --device=md1 $ROOTDEVS
raid swap --fstype=swap --level=$RAID_LEVEL --spares=$SPARE --device=md2 $SWAPDEVS
EOF
    else
      cat >> /tmp/part-include <<EOF
raid pv.01 --level=$RAID_LEVEL --spares=$SPARE --device=md1 $ROOTDEVS
volgroup main pv.01
logvol / --fstype=$FSTYPE --name=root --vgname=main --grow --size=3000
logvol swap --fstype swap --name=swap --vgname=main --recommended
EOF
    fi
  fi
fi

# display ythe contents of /tmp/part-include

echo "[$(date '+%Y-%m-%d %H:%M:%S')] === Configuration Complete ==="
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Drives Found: $NDEV"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] RAID Level: $RAID_LEVEL"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Swap Size: $SWAP_SIZE MB"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] ================================"
#cat /tmp/part-include

%end


# SME events in post-install
%post  --interpreter=/usr/bin/bash --log=/var/log/ks.post02.log
userdel -r installer
sleep 2
/sbin/e-smith/signal-event post-install
sleep 2
/sbin/e-smith/db configuration set UnsavedChanges no
touch /forcequotacheck
%end


%post  --nochroot --interpreter=/bin/bash --log=/mnt/sysimage/var/log/ks.post01.log
#!/bin/bash
sysimage="/mnt/sysimage"
cp -r /var/log/sme-partitioning.log ${sysimage}/root/
cp -r /tmp/anaconda.log ${sysimage}/root/
%end

