#!/usr/bin/env bash

# installation-help for Slax
# 22.05.2007
# shell script for installation of SLAX to harddisk
# written by Thomas Schoenhuetl <pilleus.pulcher@arcor.de> 22.05.2007
# It contains parts of the official Slackware installer.
# This shell script is contributed under the terms of GPL v2 by Thomas Schoenhuetl <pilleus.pulcher@arcor.de> 22.05.2007.

# Modified script "slax2hd" for installing Generic Linux to hdd
#   BY: Daniel K. aka *DANiO*

for i in dialog fdisk cfdisk sed grep mke2fs grub-install; do
	if [ ! -x $(command -v ${i}) ]; then
		req_app+="${i} "
		fail="true"
	fi
done
[ ${fail} ] && echo "Please install \"${req_app}\" to run this installer" && exit 1

dialog --clear --title "GENERAL INFORMATION" --msgbox "Generic installer is a gui-based tool to install your running Linux to your harddisk.\n\n You are able to partition and format your harddisk and install in the end a bootloader.\n\n You will use this installer at your own risk. I am not responsible for lost of datas or something else.\n\n If you accept this, you can start now! Or you may cancel the installer!" 20 70
if [ $? = 1 ] ; then
exit
fi

# run cfdisk to partition the harddrive
dialog --clear --title "PARTITION THE HARDDISK" --msgbox "Generic installer will now start 'cfdisk' so that you are able to create new partitions for Generic.\n\n Two partitions are recommended. 1 for the system and 1 for SWAP.\n\n I think 3 GB are enough for the root-partition - Generic plus additional programs - and twice the amount of your RAM for the swap-partition.\n\n Just follow the menu, store your changes and quit cfdisk to go on!\n\n IMPORTANT: Read the instructions and the output of cfdisk carefully. Sometimes you have to reboot to update the partition table!" 20 70
if [ $? = 1 ] ; then
exit
fi

# Create partitions using fdisk or cfdisk.
TMP=/tmp/tmp
if [ ! -d $TMP ]; then
  mkdir -p $TMP
fi

fdisk -l | grep -vE "loop|zram|ram" | sed -n 's/^Disk \(\/dev\/[^:]*\): \([^,]*\).*$/"\1" "\2" \\/p' >> $TMP/drivelist

while [ 0 ]; do
  echo dialog --ok-label Select \
    --cancel-label Continue \
    --title \"PARTITIONING\" \
    --menu \"Select drive to partition:\" 11 40 4 \\\
    > $TMP/tmpscript
  cat $TMP/drivelist >> $TMP/tmpscript
  echo "2> $TMP/tmpanswer" >> $TMP/tmpscript
  . $TMP/tmpscript
  [ $? != 0 ] && break
  PARTITION=$(cat $TMP/tmpanswer)

  if [ ! -f /etc/expert-mode ]; then
    cfdisk $PARTITION
  else
    echo dialog --title \"PARTITIONING $PARTITION\" \
      --menu \"Select which fdisk program you want to use. cfdisk is \
      strongly recommended for newbies while advanced users may prefer fdisk.\" \
      11 50 2 \
      cfdisk \"Curses based partitioning program\" \
      fdisk \"Traditional fdisk\" \
      "2> $TMP/tmpanswer" > $TMP/tmpscript
    . $TMP/tmpscript
    [ $? != 0 ] && continue
    FDISKPROGRAM=`cat $TMP/tmpanswer`
    clear
    if [ "$FDISKPROGRAM" = "cfdisk" ]; then
      cfdisk $PARTITION
    elif [ "$FDISKPROGRAM" = "fdisk" ]; then
      fdisk $PARTITION
    fi
  fi
done

rm -f $TMP/drivelist $TMP/tmpscript $TMP/tmpanswer

REDIR=/dev/tty4
NDIR=/dev/null
crunch() {
 read STRING;
 echo $STRING;
}
rm -f $TMP/SeTswap $TMP/SeTswapskip
SWAPLIST="`fdisk -l | fgrep "Linux swap" | sort 2> $NDIR`" 
if [ "$SWAPLIST" = "" ]; then
 dialog --title "NO SWAP SPACE DETECTED" --yesno "You have not created \
a swap partition with Linux fdisk.  \
Do you want to continue installing without one? " 6 60
 if [ "$?" = "1" ]; then
  dialog --title "ABORTING INSTALLATION" --msgbox "Create a swap partition with Linux fdisk, and then try this again." 6 40
  exit 1
 fi
else # there is at least one swap partition:
 echo > $TMP/swapmsg 
 if [ "$(echo "$SWAPLIST" | sed -n '2 p')" = "" ]; then
  echo "Generic Installer has detected a swap partition:\n\n" >> $TMP/swapmsg
  echo >> $TMP/swapmsg
  echo "   Device Boot    Start       End    Blocks   Id  System\\n" >> $TMP/swapmsg
  echo "`echo "$SWAPLIST" | sed -n '1 p'`\\n\n" >> $TMP/swapmsg
  echo >> $TMP/swapmsg
  echo "Do you wish to install this as your swap partition?" >> $TMP/swapmsg
  dialog --title "SWAP SPACE DETECTED" --cr-wrap --yesno "`cat $TMP/swapmsg`" 12 72
  REPLY=$?
 else
  echo "Generic Installer has detected the following swap partitions:" >> $TMP/swapmsg
  echo >> $TMP/swapmsg
  echo "   Device Boot    Start       End    Blocks   Id  System\\n" >> $TMP/swapmsg
  echo "$SWAPLIST\\n\n" >> $TMP/swapmsg
  echo >> $TMP/swapmsg
  echo "Do you wish to install these as your swap partitions? " >> $TMP/swapmsg
  dialog --title "SWAP SPACE DETECTED" --cr-wrap --yesno "`cat $TMP/swapmsg`" 13 72
  REPLY=$?
 fi
 rm -f $TMP/swapmsg
 if [ $REPLY = 0 ]; then # yes
  if grep "SwapTotal: * 0 kB" /proc/meminfo 1> $NDIR 2> $NDIR ; then
   USE_SWAP=0 # swap is not currently mounted
  else # warn of possible problems:
   # This 10231808 below is the size of a swapfile pre-supplied by install.zip that we'd like to ignore.
   if grep 10231808 /proc/meminfo 1> $NDIR 2> $NDIR ; then
    USE_SWAP=0
   else
    cat << EOF > $TMP/swapmsg
IMPORTANT NOTE: If you have already made any of your swap 
partitions active (using the swapon command), then you 
should not allow Setup to use mkswap on your swap partitions,
because it may corrupt memory pages that are currently 
swapped out.  Instead, you will have to make sure that your 
swap partitions have been prepared (with mkswap) before they
will work.  You might want to do this to any inactive swap 
partitions before you reboot.
EOF
    dialog --title "MKSWAP WARNING" --msgbox "`cat $TMP/swapmsg`" 12 67
    rm -f $TMP/swapmsg
    dialog --title "USE MKSWAP?" --yesno "Do you want Setup to use mkswap on your swap partitions?" \
    5 65
    USE_SWAP=$?
   fi
  fi
  CURRENT_SWAP="1" 
  while [ ! "`echo "$SWAPLIST" | sed -n "$CURRENT_SWAP p"`" = "" ]; do 
   SWAP_PART=`fdisk -l | fgrep "Linux swap" | sed -n "$CURRENT_SWAP p" | crunch | cut -f 1 -d ' '`
   if [ $USE_SWAP = 0 ]; then 
    dialog --title "FORMATTING SWAP PARTITION" --infobox "Formatting \
$SWAP_PART as a Linux swap partition (and checking for bad blocks)..." 4 55
    mkswap -c $SWAP_PART 1> $REDIR 2> $REDIR
   fi
   echo "Activating swap partition $SWAP_PART:"
   echo "swapon $SWAP_PART"
   swapon $SWAP_PART 1> $REDIR 2> $REDIR
   printf "%-11s %-11s %-11s %-27s %-2s %s\n" "$SWAP_PART" "swap" "swap" "defaults" "0" "0" >> $TMP/SeTswap
   CURRENT_SWAP="`expr $CURRENT_SWAP + 1`"
   sleep 1
  done
  echo "Your swapspace has been configured. This information will" > $TMP/swapmsg
  echo "be added to your /etc/fstab:" >> $TMP/swapmsg
  echo >> $TMP/swapmsg
  cat $TMP/SeTswap >> $TMP/swapmsg 
  dialog --title "SWAP SPACE CONFIGURED" --exit-label OK --textbox $TMP/swapmsg 10 72
  cat $TMP/SeTswap > $TMP/SeTfstab
  rm -f $TMP/swapmsg $TMP/SeTswap
 fi
fi  

# format root partition
fdisk -l | grep -vE "loop|zram|ram" | grep Linux | sed -e '/swap/d' | cut -b 1-9 > $TMP/pout 2>/dev/null

dialog --clear --title "ROOT PARTITION DETECTED" --exit-label OK --msgbox "Generic installer has detected\n\n `cat /tmp/tmp/pout` \n\n as your linux partition(s).\n\n In the next box you can choose the linux filesystem for your root partition or choose the partition if you have more linux partitions!" 20 70
if [ $? = 1 ] ; then
exit
fi

# choose root partition
dialog --clear --title "CHOOSE ROOT PARTITION" --inputbox "Please give me your prefered root partition in this way:\n\n /dev/hdaX --- X = number of the partition, e. g. 2 for /dev/hda2!" 10 70 2> $TMP/pout

dialog --clear --title "FORMAT ROOT PARTITION" --radiolist "Now you can choose the filesystem for your root partition.\n" 10 70 0 \
"1" "ext2" off \
"2" "ext3" off \
"3" "ext4" on \
2> $TMP/part
if [ $? = 1 ] ; then
exit
fi

if [ `cat $TMP/part` = "1" ] ; then
mkfs.ext2 `cat $TMP/pout`
dialog --clear --title "FORMAT ROOT PARTITION" --msgbox "Now your partition has been formatted with ext2 filesystem." 10 70
echo "UUID='$(blkid -s UUID -o value $(cat $TMP/pout))' / ext2 defaults 1 1" >> $TMP/SeTfstab2
# mount the root partition to copy the system
mkdir /mnt/`cat $TMP/pout | cut -b 6-9`
mount /dev/`cat $TMP/pout | cut -b 6-9` /mnt/`cat $TMP/pout | cut -b 6-9`
fi

if [ `cat $TMP/part` = "2" ] ; then
mkfs.ext3 `cat $TMP/pout`
dialog --clear --title "FORMAT ROOT PARTITION" --msgbox "Now your partition has been formatted with ext3 filesystem." 10 70
echo "UUID='$(blkid -s UUID -o value $(cat $TMP/pout))' / ext3 defaults 1 1" >> $TMP/SeTfstab2
# mount the root partition to copy the system
mkdir /mnt/`cat $TMP/pout | cut -b 6-9`
mount /dev/`cat $TMP/pout | cut -b 6-9` /mnt/`cat $TMP/pout | cut -b 6-9`
fi

if [ `cat $TMP/part` = "3" ] ; then
mkfs.ext4 `cat $TMP/pout`
dialog --clear --title "FORMAT ROOT PARTITION" --msgbox "Now your partition has been formatted with ext4 filesystem." 10 70
echo "UUID='$(blkid -s UUID -o value $(cat $TMP/pout))' / ext4 defaults 1 1" >> $TMP/SeTfstab2
# mount the root partition to copy the system
mkdir /mnt/`cat $TMP/pout | cut -b 6-9`
mount /dev/`cat $TMP/pout | cut -b 6-9` /mnt/`cat $TMP/pout | cut -b 6-9`
fi

# copy the system
dialog --clear --title "COPYING THE SYSTEM" --msgbox "Generic installer will now copy the running system to your harddisk.\n\n Press OK to start ..." 10 70
if [ $? = 1 ] ; then
exit
fi 

echo "rsync --force -ar /run/initramfs/memory/system/* /mnt/`cat $TMP/pout | cut -b 6-9`" > $TMP/rsync_cmd
chmod +x $TMP/rsync_cmd

#from: https://www.linuxquestions.org/questions/programming-9/dialog-command-buffering-problem-in-pipe-4175423593/#post4762038
dialog --title "COPYING PROCESS" --msgbox "Generic installer is copying the system to your harddisk.\n\n Please be patient ... it may take up to 10 minutes depending on your system!" 10 70
$TMP/rsync_cmd

mkdir -p /mnt/`cat $TMP/pout | cut -b 6-9`/dev /mnt/`cat $TMP/pout | cut -b 6-9`/proc /mnt/`cat $TMP/pout | cut -b 6-9`/sys /mnt/`cat $TMP/pout | cut -b 6-9`/tmp

dialog --clear --title "TRANSACTION FINISHED" --msgbox "Now Generic installer has finished the transaction." 10 70
if [ $? = 1 ] ; then
exit
fi

# create new fstab
cat $TMP/SeTfstab > /mnt/`cat $TMP/pout | cut -b 6-9`/etc/fstab 2>/dev/null
cat $TMP/SeTfstab2 >> /mnt/`cat $TMP/pout | cut -b 6-9`/etc/fstab 2>/dev/null

mount --bind /dev /mnt/`cat $TMP/pout | cut -b 6-9`/dev
mount --bind /proc /mnt/`cat $TMP/pout | cut -b 6-9`/proc
mount --bind /sys /mnt/`cat $TMP/pout | cut -b 6-9`/sys

grub-install --recheck --force --root-directory=/mnt/`cat $TMP/pout | cut -b 6-9` `cat $TMP/pout | cut -b 1-8`
if ! chroot /mnt/`cat $TMP/pout | cut -b 6-9` grub-mkconfig -o /boot/grub/grub.cfg; then
	# if here is error then panic!
	dialog --title "ERROR" --infobox "Can't generate grub.cfg file!\n---\nI'm panic!\n" 10 70
	umount -f /mnt/`cat $TMP/pout | cut -b 6-9`/dev /mnt/`cat $TMP/pout | cut -b 6-9`/proc /mnt/`cat $TMP/pout | cut -b 6-9`/sys
	#umount -f /mnt/`cat $TMP/pout | cut -b 6-9`
	exit 1
fi

umount -f /mnt/`cat $TMP/pout | cut -b 6-9`/dev /mnt/`cat $TMP/pout | cut -b 6-9`/proc /mnt/`cat $TMP/pout | cut -b 6-9`/sys

rm -f /mnt/`cat $TMP/pout | cut -b 6-9`/etc/hostname
while :; do
	clear
	echo "What is your hostname (computer name)?"
	read hostname
	if [ -z "$hostname" ]; then
		clear
		echo "This hostname can not be empty"
		sleep 2
	else
		echo "$hostname" >/mnt/`cat $TMP/pout | cut -b 6-9`/etc/hostname
		break
	fi
done

echo "Installation completed!
--------------------------------"
sleep 4

rm -rf $TMP
while :; do
	clear
	echo -e "Would you like to reboot in to new system?\n[Y]es or [N]o?\n"
	read choice
	case $choice in
	[Yy][Ee][Ss]|[Yy]) reboot ;;
	[Nn][Oo]|[Nn]) exit ;;
	*) echo "Bad option '${choice}'"; sleep 2 ;;
	esac
done
