#!/bin/bash

# This script is used to install and setup a sandbox.

PACKAGES=(
    "linux-lts" "linux-firmware" "base" "base-devel" "syslinux" "vi" "emacs" "vim" "nano"
    "micro" "neovim" "bash-completion" "btop" "gdu" "neofetch" "git" "curl" "wget" "rsync"
    "unzip" "zip" "gdb" "jdk-openjdk" "openjdk-doc" "tcpdump" "openssh" "bind" "inetutils"
    "nmap" "firefox" "firefox-i18n-fr" "libreoffice" "libreoffice-fr" "rpcbind" "nfs-utils"
    "xfce4" "xfce4-goodies" "yakuake" "gimp" "xorg" "xf86-video-vesa" "xf86-video-dummy"
    "ttf-dejavu" "ttf-liberation" "ttf-bitstream-vera" "acpid" "sdl12-compat" "sdl_ttf"
    "sdl_gfx" "sdl_image" "sdl_mixer" "sdl_net" "sdl_sound" "sdl2_gfx" "sdl2_image"
    "sdl2_mixer" "sdl2_net" "sdl2_ttf" "dosfstools" "ntfs-3g" "ntp" "subversion" "cvs" "git"
    "breezy" "python" "wireshark-qt" "wireshark-cli" "evince" "dbus" "mlocate" "gvfs"
    "strace" "net-tools" "postfix" "sudo" "gtksourceview3" "mplayer" "cronie" "optipng"
    "lib32-glibc" "libvirt" "qt5" "xterm" "graphviz" "vlc" "pulseaudio" "pulseaudio-alsa"
    "tmux" "sleuthkit" "tk" "tcl" "xterm" "junit" "lightdm" "samba" "bind" "krb5" "tree"
    "time" "noto-fonts" "noto-fonts-cjk" "noto-fonts-emoji" "noto-fonts-extra" "numlockx"
    "lightdm-gtk-greeter" "tigervnc" "xfce4-pulseaudio-plugin" "docker" "docker-compose"
    "android-tools" "opam"
)

PACKAGES_AUR=(
    "imunes" "saxon6" "staruml" "xfce4-pulseaudio-plugin" "pa-applet-git" "sublime-text"
    "android-studio" "android-sdk" "android-sdk-platform-tools" "android-sdk-build-tools"
    "android-platform" "android-platform-21" "oracle-instantclient-basic"
    "oracle-sqldeveloper" "oracle-instantclient-jdbc" "oracle-instantclient-odbc"
    "oracle-instantclient-sdk" "oracle-instantclient-sqlplus" "oracle-instantclient-tools"
    "ncurses5-compat-libs"
)

SERVICES=(
    "systemd-networkd.service" "systemd-resolved.service" "systemd-timesyncd.service"
    "fstrim.service" "docker.service" "ovs-vswitchd.service" "marionnet.service"
)

SWAP_SIZE=16G

# Enable time synchronization
timedatectl set-ntp true

# Wait for the clock to be synchronized
while :; do
    timedatectl status | grep "synchronized: yes" && break
    sleep 1
done

# Wait a few seconds for everything to be ready
sleep 20

# Switch the disk to MBR without confirmation
parted /dev/sda mklabel msdos --script

# Create the swap and root partitions
parted /dev/sda mkpart primary linux-swap 1MiB $SWAP_SIZE --script
parted /dev/sda mkpart primary ext4 $SWAP_SIZE 100% --script

# Format the partitions
mkswap /dev/sda1
mkfs.ext4 /dev/sda2 -F

# Mount the partitions
swapon /dev/sda1
mount /dev/sda2 /mnt

# Enable parallel downloads in pacman
sed -i "s/#ParallelDownloads = 5/ParallelDownloads = 16/" /etc/pacman.conf

# Update the keyring
pacman -Sy --noconfirm archlinux-keyring

# Install the base system
pacstrap -K /mnt "${PACKAGES[@]}"

# Generate the fstab file
genfstab -U /mnt >>/mnt/etc/fstab

# Chroot into the new system
arch-chroot /mnt /bin/bash <<EOF
# Disable history in the shell
set +o history

# Set the timezone
ln -sf /usr/share/zoneinfo/Europe/Paris /etc/localtime

# Set the hardware clock time standard
hwclock --systohc

# Generate the locales
sed -i "s/#en_US.UTF-8 UTF-8/en_US.UTF-8 UTF-8/" /etc/locale.gen
sed -i "s/#fr_FR.UTF-8 UTF-8/fr_FR.UTF-8 UTF-8/" /etc/locale.gen
locale-gen

# Set the default locale
echo "LANG=en_US.UTF-8" > /etc/locale.conf

# Set the keyboard layout
echo "KEYMAP=fr-latin1" > /etc/vconsole.conf

# Set the hostname
echo "sandbox" > /etc/hostname

# Set the root password
echo "root:root" | chpasswd

# Install syslinux
syslinux-install_update -iam

# Configure the network for DHCP
echo "[Match]
Name=en*

[Network]
DHCP=yes
" > /etc/systemd/network/20-wired.network

# Enable automatic root login in the console
mkdir -p /etc/systemd/system/getty@tty1.service.d/
echo "[Service]
ExecStart=
ExecStart=-/usr/bin/agetty --autologin root --noclear %I \$TERM
" > /etc/systemd/system/getty@tty1.service.d/autologin.conf

# Create a service that runs fstrim -va on startup and shutdown
echo "[Unit]
Description=Discard unused blocks on the root filesystem
After=multi-user.target

[Service]
Type=oneshot
ExecStart=
ExecStop=/usr/bin/fstrim -va
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
" > /etc/systemd/system/fstrim.service

# Create the syslinux configuration file, to instantly boot into the system
echo "DEFAULT arch
LABEL arch
    LINUX ../vmlinuz-linux-lts
    INITRD ../initramfs-linux-lts.img
    APPEND root=/dev/sda2 rw resume=/dev/sda1
" > /boot/syslinux/syslinux.cfg

# Enable case-insensitive completion
echo 'set completion-ignore-case On' >> /etc/inputrc

# Install AUR packages
useradd --no-user-group -g users --create-home --home-dir /tmp/aur-install aur-install
echo "aur-install ALL=(ALL) NOPASSWD: ALL" > /etc/sudoers.d/aur-install
su aur-install
cd /tmp/aur-install
git clone https://aur.archlinux.org/yay.git
cd yay
makepkg --syncdeps --install --needed --noconfirm
yay -Syu --noconfirm "${PACKAGES_AUR[@]}"
exit
rm /etc/sudoers.d/aur-install
userdel --remove --force aur-install

# Android Studio config
echo "
# DRI video devices
SUBSYSTEM==\"drm\", KERNEL==\"card*|renderD*\", MODE=\"0666\"

# Enable access to virtualization device to all users
SUBSYSTEM==\"misc\", KERNEL==\"kvm\", MODE=\"0666\"
" >> /etc/udev/rules.d/65-kvm.rules
# ajouter le fichier /etc/X11/xorg.conf.d/20-radeon.conf
echo "Section \"DRI\"
        Mode 0666
EndSection" >> /etc/X11/xorg.conf.d/20-radeon.conf
chmod 1755 /opt/android-sdk/platform-tools/adb
chmod 1755 /opt/android-sdk/tools/emulator

# Installation de la librairie graphique de Denis
cd /tmp
wget -O bibliotheque-graphique-iut-1.1.tar.gz https://grond.iut-fbleau.fr/IUT/bibliotheque-graphique/archive/1.1.tar.gz
tar xzvf bibliotheque-graphique-iut-1.1.tar.gz
cd bibliotheque-graphique
./configure
make
make install

# Install Marionnet
cd /tmp
wget -O marionnet_from_scratch https://www.marionnet.org/site/index.php/fr/documentation/installation/from-scratch
chmod +x
PREFIX=$(marionnet --paths | awk '/share.marionnet.filesystem/ {print $3}') 
PREFIX=${PREFIX%share/marionnet/filesystems}
./marionnet_from_scratch -O -p $PREFIX -s 0.90.x

# Create a service for Marionnet
echo "[Unit]
Description=Daemon for Marionnet

[Service]
ExecStart=/usr/local/bin/marionnet-daemon.native

[Install]
WantedBy=multi-user.target
" > /etc/systemd/system/marionnet.service

# Enable the services
systemctl enable "${SERVICES[@]}"

EOF

# Unmount the partitions
swapoff /dev/sda1
umount -R /mnt