#!/bin/bash
set -e
clear
# detect primary disk
DISK=""
for d in $(ls /sys/block | grep -v "^dm" | grep -v "^fd"); do
    if echo $d | grep loop >/dev/null; then
        continue
    fi
    if [[ "0" == "$(cat /sys/block/$d/removable)" ]] && [[ "$(realpath /sys/block/$d | grep usb)" == "" ]] ; then
        DISK="$d"
        break
    fi
done

# detect disk prefix
if echo ${DISK} | grep nvme ; then
    DISKX=${DISK}p
else
    DISKX=${DISK}
fi

echo $DISKX

if [[ $$ -eq 1 ]] ; then
    # cttyhack
    exec >/dev/tty1
    exec </dev/tty1
    exec 2>/dev/tty1
fi

# fallback functions
function fallback(){
    echo -e "\033[31;1mInstallation failed.\033[;0m"
    echo -e "Creating a shell for debuging. Good luck :D"
    PS1="\[\033[32;1m\]>>>\[\033[;0m\]" /bin/bash --norc --noprofile
    if [[ $$ -eq 1 ]] ; then
        echo o > /proc/sysrq-trigger
    else
        exit 1
    fi
}

# create partitions
if [[ -d /sys/firmware/efi ]] ; then
    parted -s /dev/${DISK} mktable gpt || fallback
    parted -s /dev/${DISK} mkpart primary fat32 1 "100MB" || fallback
    parted -s /dev/${DISK} mkpart primary fat32 100MB "100%" || fallback
    sync && sleep 1
    yes | mkfs.vfat /dev/${DISKX}1 || fallback
    sync && sleep 1
    yes | mkfs.ext4  /dev/${DISKX}2 || fallback
    yes | parted /dev/${DISK} set 1 esp on || fallback
    sync && sleep 1
    mkdir -p /target/ || true
    mount /dev/${DISKX}2  /target || fallback
    mkdir -p /target/boot/efi || true
    mount /dev/${DISKX}1 /target/boot/efi  || fallback
else
    parted -s /dev/${DISK} mktable msdos || fallback
    parted -s /dev/${DISK} mkpart primary fat32 1 "100%" || fallback
    sync && sleep 1
    yes | mkfs.ext4 /dev/${DISKX}1  || fallback
    yes | parted /dev/${DISK} set 1 boot on || fallback
    sync && sleep 1
    mkdir -p /target/ || true
    mount /dev/${DISKX}1 /target  || fallback
fi

# Copy rootfs
mkdir -p /source
mount /dev/loop0 /source || fallback
clear
rsync --archive --info=progress2 --no-inc-recursive --human-readable --hard-links --xattrs --acls -r /source/ /target/
sync
clear

# bind system
for dir in dev sys proc run ; do
    mount --bind /$dir /target/$dir || fallback
done

# reduce initramfs file size
#sed -i "s/MODULES=most/MODULES=dep/g" /target/etc/initramfs-tools/initramfs.conf

# remove live packages
chroot /target apt-get purge live-boot* live-config* live-tools --yes || true
chroot /target apt-get autoremove --yes || true
chroot /target update-initramfs -u -k all  || fallback

# install grub
if [[ -d /sys/firmware/efi ]] ; then
    chroot /target mount -t efivarfs efivarfs /sys/firmware/efi/efivars || true
    chroot /target grub-install /dev/${DISK} --target=x86_64-efi || fallback
    chroot /target grub-install /dev/${DISK} --removable --target=x86_64-efi || fallback
    uuid_efi=$(blkid  /dev/${DISKX}1 | sed "s/ /\n/g" | grep "^UUID")
    uuid_rootfs=$(blkid  /dev/${DISKX}2 | sed "s/ /\n/g" | grep "^UUID")
    echo "${uuid_efi} /boot/efi vfat defaults,rw 0 0" > /target/etc/fstab
    echo "${uuid_rootfs} / ext4 defaults,rw 0 1" >> /target/etc/fstab
else
    chroot /target grub-install /dev/${DISK} --target=i386-pc || fallback
    uuid_rootfs=$(blkid  /dev/${DISKX}1 | sed "s/ /\n/g" | grep "^UUID")
    echo "${uuid_rootfs} / ext4 defaults,rw 0 1" >> /target/etc/fstab
fi
chroot /target grub-mkconfig -o /boot/grub/grub.cfg || fallback

# X11 keyboard
cat > /target/etc/X11/xorg.conf.d/10-keyboard.conf << EOF
Section "InputClass"
Identifier "system-keyboard"
MatchIsKeyboard "on"
Option "XkbLayout" "tr"
Option "XkbModel" "pc105"
#Option "XkbVariant" "f"
EndSection
EOF

# Language
echo "tr_TR.UTF-8 UTF-8" > /target/etc/locale.gen
echo "en_US.UTF-8 UTF-8" >> /target/etc/locale.gen
echo "LANG=tr_TR.UTF-8" > /target/etc/default/locale
echo "LC_CTYPE=en_US.UTF-8" >> /target/etc/default/locale
echo "Europe/Istanbul" > /target/etc/timezone
chroot /target timedatectl set-timezone Europe/Istanbul || true
rm -f /target/etc/localtime  || true
ln -s ../usr/share/zoneinfo/Turkey /target/etc/localtime
chroot /target locale-gen

# Hosts file
echo "etap" > /target/etc/hostname
echo "127.0.0.1 localhost" > /target/etc/hosts
echo "127.0.1.1 etap" >> /target/etc/hosts
echo "" >> /target/etc/hosts
echo "# The following lines are desirable for IPv6 capable hosts" >> /target/etc/hosts
echo "::1     localhost ip6-localhost ip6-loopback" >> /target/etc/hosts
echo "ff02::1 ip6-allnodes" >> /target/etc/hosts
echo "ff02::2 ip6-allrouters" >> /target/etc/hosts

# sources.list
rm -f /target/etc/apt/sources.list.d/pardus-yirmiuc.list
cat > /target/etc/apt/sources.list <<EOF
### Official Pardus ETAP Package Repositories ###

## ETAP
deb http://depo.etap.org.tr/etap yirmiuc main contrib non-free non-free-firmware
# deb-src http://depo.etap.org.tr/etap yirmiuc main contrib non-free non-free-firmware

## Pardus
deb http://depo.etap.org.tr/pardus yirmiuc main contrib non-free non-free-firmware
# deb-src http://depo.etap.org.tr/pardus yirmiuc main contrib non-free non-free-firmware

## Pardus Deb
deb http://depo.etap.org.tr/pardus yirmiuc-deb main contrib non-free non-free-firmware
# deb-src http://depo.etap.org.tr/pardus yirmiuc-deb main contrib non-free non-free-firmware

## Pardus Security Deb
deb http://depo.etap.org.tr/guvenlik yirmiuc-deb main contrib non-free non-free-firmware
# deb-src http://depo.etap.org.tr/guvenlik yirmiuc-deb main contrib non-free non-free-firmware
EOF

# Create user
chroot /target useradd -m etapadmin -c "Etap Yetkili" -G cdrom,floppy,sudo,audio,dip,video,plugdev,netdev,bluetooth,scanner,lpadmin -s /bin/bash -p '$6$tw.jf1LotqtJb8$.jSt8UWVZ0LQKfwDmZ7.feXSfr2Ijxy.uMtaG.8Txok05FmfFf1f31.gugLk8sitcKBjmHEDUiEpdOdADvsww0' -U
chroot /target useradd -m ogretmen -c "Öğretmen" -G cdrom,floppy,audio,dip,video,plugdev,netdev,bluetooth,scanner,lpadmin -s /bin/bash -p '$6$TDARTWfgY6peM7fc$TC9AOo/4rzGnegnVN3p3ugSTbgJyO2hTcha3hoEIHtUh8fhzHCLnxzPxQPHlfmNnGeGpo165VPRe.JHvuN4BW1' -U
chroot /target useradd -m ogrenci -c "Sınırlı Erişim" -G audio,video -s /bin/bash -p XKIuFXArmd2jU -U

if [[ -f /target/sbin/sshd ]] ; then
    chroot /target ssh-keygen -A
fi

sync

# unbind
for dir in dev sys proc run ; do
    while umount -lf -R /target/$dir ; do
        :
    done
done

# reboot / exit

echo s > /proc/sysrq-trigger
echo u > /proc/sysrq-trigger
echo b > /proc/sysrq-trigger
