#!/bin/bash

if [ "$(id -u)" -ne 0 ]; then
    kdialog --sorry  "<p allign="center">Dieses Programm benötigt Root-Rechte! Beende.<br />That programm needs root rights! Exiting.</p>" 2>/dev/null
    exit 1
fi

LLANG=$(echo $LANG|awk -F_ '{print $2}'|awk -F\. '{print $1}')
rm -f /home/tux/.config/plasma-localerc

#LLANG=$(kdialog --title "Sprache / Language" --combobox "Wählen Sie ihre Sprache / Choose your language" --default "$LANGUAGE" "DE" "EN")
IS_TUX=$(dmidecode|grep -m1 -i tuxedo| awk '{print $2}')

lsblk | awk '/disk/{ print $1 }' | sort >/tmp/disklist2
for m in $(lsblk -lf -o Name,TYPE,FSTYPE | grep ntfs | awk '{ print $1 }' | egrep "sd|hd|vd" | cut -c1-3 | sort | uniq); do sed -i "/\<$m\>/d" /tmp/disklist2; done
for n in $(lsblk -lf -o Name,TYPE,FSTYPE | grep ntfs | awk '{ print $1 }' | grep nvme | cut -c1-7 | sort | uniq); do sed -i "/\<$n\>/d" /tmp/disklist2; done
for e in $(lsblk -lf -o Name,TYPE,SUBSYSTEMS | grep usb | awk '/disk/{ print $1 }'| sort | uniq); do sed -i "/\<$e\>/d" /tmp/disklist2; done

if [ ! $IS_TUX ]; then
	if [ $LLANG = "DE" ]; then
		kdialog --msgbox "Sie wollen TUXEDO OS auf einem Nicht-TUXEDO-Gerät installieren,\n Software, wie Tomte oder TUXEDO Control Center wird nicht,\n oder nur eingeschränkt funktionieren." 2>/dev/null
	else
    		kdialog --msgbox "You are going to install TUXEDO OS on a non-TUXEDO device,\n software like Tomte or TUXEDO Control Center will not work,\n or will work only limited." 2>/dev/null
	fi
else
    if [ -f /usr/bin/tomte ]; then
	while [ ! $(grep -i -m1 finished /var/log/tomte/tomte.log | awk '{print $1}') ]
	do echo "" > /dev/null
	sleep 1
	done | zenity --progress --text "tomte installiert noch fixes. Die Installation geht gleich weiter.\ntomte is installing fixes. The installation will continue after that" --title "tomte arbeitet / tomte is running" --no-cancel --pulsate --auto-close 2>/dev/null
    fi
fi
find_device_de() {
lsblk | awk '/disk/{ print $1 }' | sort >/tmp/disklist
for m in $(lsblk -lf -o Name,TYPE,FSTYPE | grep ntfs | awk '{ print $1 }' | egrep "sd|hd|vd" | cut -c1-3 | sort | uniq); do sed -i "/\<$m\>/d" /tmp/disklist; done
for n in $(lsblk -lf -o Name,TYPE,FSTYPE | grep ntfs | awk '{ print $1 }' | grep nvme | cut -c1-7 | sort | uniq); do sed -i "/\<$n\>/d" /tmp/disklist; done
for e in $(lsblk -lf -o Name,TYPE,SUBSYSTEMS | grep usb | awk '/disk/{ print $1 }'| sort | uniq); do sed -i "/\<$e\>/d" /tmp/disklist; done
device=$(kdialog --icon /usr/share/icons/tuxedo-breeze/apps/48x48/calamares.png --title Laufwerke --combobox "<p align="center"><h3>Wählen Sie die Zielplatte für TUXEDO OS.</h3><hr></hr><font style="color:red">Es werden nur Platten angezeigt,die keine NTFS Partitionen beinhalten!</font><br /></p>" 2>/dev/null $(cat /tmp/disklist | awk '{printf $0" "}')
)
if [ -z "$device" ]; then
  kdialog --icon /usr/share/tuxedo/icons/calamares.png --sorry "<p><h3>Keine Platte gewählt.</h3> Wurde keine Platte gelistet, dann enthält ihre Platte eine oder mehrere NTFS Partition(en).<br />Verschlüsselung wird in diesem Fall nicht unterstützt, starten Sie die Installation normal,<br />indem sie bei der Frage zur Verschlüsselung 'Nein' wählen.</p>" 2>/dev/null
  echo $device
  exit
fi
}

find_device_en() {
lsblk | awk '/disk/{ print $1 }' | sort >/tmp/disklist
for m in $(lsblk -lf -o Name,TYPE,FSTYPE | grep ntfs | awk '{ print $1 }' | egrep "sd|hd|vd" | cut -c1-3 | sort | uniq); do sed -i "/\<$m\>/d" /tmp/disklist; done
for n in $(lsblk -lf -o Name,TYPE,FSTYPE | grep ntfs | awk '{ print $1 }' | grep nvme | cut -c1-7 | sort | uniq); do sed -i "/\<$n\>/d" /tmp/disklist; done
for e in $(lsblk -lf -o Name,TYPE,SUBSYSTEMS | grep usb | awk '/disk/{ print $1 }'| sort | uniq); do sed -i "/\<$e\>/d" /tmp/disklist; done
device=$(kdialog --icon /usr/share/icons/tuxedo-breeze/apps/48x48/calamares.png --title Laufwerke --combobox "<p align="center"><h3>Choose a target device for TUXEDO OS.</h3><hr></hr><font style="color:red">Only disks that do not contain NTFS partitions are displayed!</font><br /></p>" 2>/dev/null $(cat /tmp/disklist | awk '{printf $0" "}'))
if [ -z "$device" ]; then
  kdialog --icon /usr/share/tuxedo/icons/calamares.png --sorry "<p><h3>No disk selected.</h3>If no disk was listed, then your plate contains one or more NTFS partition(s).<br />Encryption is not supported in this case, start the installation normally,<br />by selecting 'No' in the encryption question.</p>" 2>/dev/null
  exit
fi
}

prepare_disk() {
    parted --script /dev/${device} \
          mklabel gpt \
          mkpart primary ext3 1MiB 1025MiB \
          mkpart primary fat32 1025MiB 1537MiB \
          mkpart primary 1537MiB 100% \
          name 1 BOOT \
          name 2 EFI \
          name 3 CRYPT \
          set 2 esp on \
          print \
          quit \

    nvme=$(echo $device | cut -c1-4)
    if [ $nvme = "nvme" ]; then
     part="p"
    else
     part=""
    fi
    echo ${lukspw} | cryptsetup -q luksFormat /dev/${device}${part}3
    echo ${lukspw} | cryptsetup -q luksOpen /dev/${device}${part}3 crypt_dev_${device}${part}3
    pvcreate /dev/mapper/crypt_dev_${device}${part}3
    vgcreate system /dev/mapper/crypt_dev_${device}${part}3
    swapsize=$(LANG=C free -m | awk '/Mem/{ print $2 }')
    lvcreate -n swap -L ${swapsize}MiB system
    lvcreate -n root -l 100%FREE system
    echo ${device}${part}1
    echo ${device}${part}2
    mkfs.ext4 /dev/system/root
    mkswap /dev/system/swap
    mkfs.ext3 /dev/${device}${part}1 -L BOOT<<EOF
y
EOF
    mkfs.vfat /dev/${device}${part}2 -n EFI
}
prepare_target() {
    nvme=$(echo $device | cut -c1-4)
    if [ $nvme = "nvme" ]; then
     part="p"
    else
     part=""
    fi
    mount /dev/system/root /mnt
    mkdir -p /mnt/boot
    mount /dev/${device}${part}1 /mnt/boot
}

check_mounts_de() {
    mounted=$(grep -m1 mnt /proc/mounts|awk '{ print $1 }')
    if [ -z ${mounted} ]; then
	kdialog --error "Das hat nicht funktioniert, das Ziel ist nicht gemountet" 2>/dev/null
	exit
    fi
}

check_mounts_en() {
    mounted=$(grep -m1 mnt /proc/mounts|awk '{ print $1 }')
    if [ -z  ${mounted} ]; then
	kdialog --error "There is something wrong, target not mounted" 2>/dev/null
	exit
    fi
}

rsync_task() {
    rsync -aAXv / --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found","/boot/efi","/fll"} /mnt
}
calamares_task() {
    nvme=$(echo $device | cut -c1-4)
    if [ $nvme = "nvme" ]; then
     part="p"
    else
     part=""
    fi
    mkdir -p /mnt/boot/efi
    mount /dev/${device}${part}2 /mnt/boot/efi
    for i in /dev /dev/pts /proc /sys /sys/firmware/efi/efivars /run; do sudo mount -B $i /mnt$i; done
    chroot /mnt rm -r /etc/calamares
    chroot /mnt ln -s /usr/share/tuxedo/calamares-oem /etc/calamares
    chroot /mnt calamares
}
finished_task_de() {
    if kdialog --title "Fertig" --yesno "<p align="center">Installation beendet, wollen sie das System neu starten?</p>" 2>/dev/null
        then
        systemctl reboot
    else
	vgchange -a n system
	cryptsetup luksClose crypt_dev_${device}${part}3
	exit
    fi
}
finished_task_en() {
    if kdialog --title "Finished" --yesno "<p align="center">Installation finished, do you want to restart the system?</p>" 2>/dev/null
        then
          systemctl reboot
    else
	vgchange -a n system
	cryptsetup luksClose crypt_dev_${device}${part}3
	exit
    fi
}
if [ -e /sys/firmware/efi ]; then
    if [ $LLANG = "DE" ]; then
	if [ -z "$(cat /tmp/disklist2)" ]; then
	    calamares
	else
	    if kdialog --title "*** Verschlüsselte Installation ***" --warningyesno "Wollen Sie eine verschlüsselte Installation machen?\nEs wird die komplette Platte verwendet.\nAlle Daten auf dieser Platte werden gelöscht.\nWenn Sie das nicht wollen, wählen sie 'Nein'." 2>/dev/null
    		then
    		find_device_de
		kdialog --title "Partitionierung" --msgbox "Die folgenden Partitionen werden auf /dev/${device} erzeugt:\n\nPartition 1:       1024    MiB     Boot \nPartition 2:         512    MiB     EFI \nPartition 3:       Rest    MiB     LUKS2 \n" 2>/dev/null
		ERC=1
		until [ $ERC -ne 1 ]
		    do
    		    if ! CPASSW1=$(kdialog --title="Neues LUKS Passwort" --password "Bitte geben Sie ein Passwort für die LUKS Verschlüsselung ein." 2>/dev/null); then
			kdialog --msgbox "Kein Passwort eingegeben, breche ab." 2>/dev/null
			exit 0;
		    fi
    		    if ! CPASSW2=$(kdialog --title="Neues LUKS Passwort" --password "Bitte wiederholen Sie das Passwort für die LUKS Verschlüsselung." 2>/dev/null); then
			kdialog --msgbox "Kein Passwort eingegeben, breche ab." 2>/dev/null
			exit 0;
		    fi
		    sleep 1
		    if [ "$CPASSW1" == "$CPASSW2" ]; then
			set +H
			ERC=0
			lukspw=${CPASSW1}
			break;
		    else
		        ERC=1
			kdialog --error "Passwort ist nicht gleich" 2>/dev/null
		    fi
		done
    		prepare_disk | zenity --progress --title="Arbeite an der Partitionierung ..." --pulsate --no-cancel --width=400 --auto-close
    		prepare_target
		check_mounts_de
    		rsync_task | zenity --progress --title="Arbeite .... " --text="Kopiere Livesystem ins Ziel ..., starte dann den grafischen Installer." --pulsate --no-cancel --width=400 --auto-close
    		calamares_task
    		umount -R /mnt
		finished_task_de
    	    else
    		calamares
	    fi
	fi
    else
	if kdialog --title "*** Crypted Install ***" --warningyesno "Will you do a crypted installation and erase all data on the selected disk?\nThe whole disk will be used.\nIf you don't want that, hit 'No'." 2>/dev/null
    	    then
    	    find_device_en
	    kdialog --title "Partitions" --msgbox "The following partitions will be created on /dev/${device}\n\nPartition 1:       1024    MiB     Boot \nPartition 2:         512    MiB     EFI \nPartition 3:       Rest    MiB     LUKS2 \n" 2>/dev/null
	    ERC=1
	    until [ $ERC -ne 1 ]
		do 
    		if ! CPASSW1=$(kdialog --title="New LUKS password" --password "Please enter a new password for LUKS encryption." 2>/dev/null); then
		    kdialog --error "No password given, exit."
		    exit 0;
		fi
    		if ! CPASSW2=$(kdialog --title="New LUKS password" --password "Please repeat the new password for LUKS encryption." 2>/dev/null); then
		    kdialog --error "No password given, exit."
		    exit 0;
		fi
		sleep 1
		if [ "$CPASSW1" == "$CPASSW2" ]; then
		    set +H
		    ERC=0
		    lukspw=${CPASSW1}
		    break;
		else
		    ERC=1
		    kdialog --error "Passwort ist nicht gleich" 2>/dev/null
		fi
	    done
    	    prepare_disk | zenity --progress --title="Working on Partitions ..." --pulsate --no-cancel --width=400 --auto-close
    	    prepare_target
	    check_mounts_en
    	    rsync_task | zenity --progress --title="Working .... " --text="Copy livesystem to target, start the graphical installer after rsync." --pulsate --no-cancel --width=400 --auto-close
    	    calamares_task
    	    umount -R /mnt
	    finished_task_en
	else
    	    calamares
	fi
    fi
else
    calamares
fi
exit 0
