# Exit on error
set -e

# Postinstallation script for Fedora 36.

# let's be careful and git clone as an unprivileged user
install_helix_unprivileged() {
	cd ~/.gitclone
	git clone https://github.com/helix-editor/helix
	ln -s helix/runtime ~/.config/helix/runtime
}

# these install_* functions are being run as root
install_helix() {
	sudo -u $ORIGINAL_USER bash -c "$(declare -f install_helix_unprivileged); install_helix_unprivileged"
	cargo install --root /usr/local --path $ORIGINAL_HOME/.gitclone/helix/helix-term
}

install_nano() {
	dnf install nano -y
}

install_nvim() {
	dnf install neovim -y
}

# Postinstall stage 1 (tasks that have to be run as root)
stage1_root() {

	# DNF options to sweeten life.
	echo "defaultyes=True" | tee -a /etc/dnf/dnf.conf >/dev/null
	echo "fastestmirror=True" | tee -a /etc/dnf/dnf.conf >/dev/null
	echo "maxparalleldownloads=10" | tee -a /etc/dnf/dnf.conf >/dev/null
	
	# Full system update, important after an install.
	dnf upgrade -y
	
	# Install dialog for communication with the user running this :)
	dnf install dialog -y
	
	editor=$(dialog --no-cancel --title "Select Editor" --radiolist "Choose a terminal text editor to install:" 0 0 3 1 "helix" on 2 "nano" off 3 "neovim" off 4 "none" off --stdout)
	dualboot=$(dialog --no-cancel --title "Dualboot" --radiolist "Are you going to be using other operating systems, or only Fedora?" 0 0 3 1 "Other OSes too (enable boot menu)" on 2 "Just Fedora (skip boot menu)" off --stdout)
	
	# Enable the RPM fusion free repositories.
	dnf install -y https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm
	
	# Install a few packages: cargo to compile Helix later, the almighty Z shell (sorry bash), bat (like cat but better), gnome-tweaks, appimagelauncher (for AppImage integration), util-linux-user (for chsh), neofetch (BECAUSE NEOFETCH), htop (quite nice I would say), vlc (for all video needs), git (essential), sqlite (to delete bookmarks), some nice nautilus plugins, cURL (kindof essential) and the g++ compiler.
	dnf install cargo zsh bat gnome-tweaks g++ util-linux-user neofetch htop vlc git sqlite nautilus-image-converter curl https://github.com/TheAssassin/AppImageLauncher/releases/download/v2.2.0/appimagelauncher-2.2.0-travis995.0f91801.x86_64.rpm -y
	
	# Install media codecs.
	dnf install -y gstreamer1-plugins-{bad-\*,good-\*,base} gstreamer1-plugin-openh264 gstreamer1-libav --exclude=gstreamer1-plugins-bad-free-devel
	
	# Add the flathub remote to Flatpak. (Fedora has flatpak but disables flathub by default)
	flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
	flatpak remote-modify --enable flathub

	# Install the Extension Manager app globally.
	flatpak install flathub com.mattjakeman.ExtensionManager -y
	
	# I was going to force Helix but let's give a choice, just in case.
	case $editor in
		1) install_helix;;
		2) install_nano;;
		3) install_nvim;;
		*) echo "No editor selected";;
	esac
	
	# Set the hostname
	hostnamectl hostname $NEW_HOSTNAME
	
	case $dualboot in
		# Update grub to boot Fedora instantly (yeah, no dualboot)
		2) sed "s/GRUB_TIMEOUT=[0-9]/GRUB_TIMEOUT=0/g" -i /etc/default/grub; grub2-mkconfig -o /boot/grub2/grub.cfg;;
		*) echo "Not skipping boot menu";;
	esac
	
	# Change shell to ZSH
	chsh -s $(which zsh) $ORIGINAL_USER
	
	# Install the Starship prompt.
	curl -sS https://starship.rs/install.sh > /tmp/starship-install.sh
	sh /tmp/starship-install.sh -y
	
	# Save Stage 2 for autostart on next login.
	declare -f stage2 > /usr/local/bin/fedora-postinstall-stage2
	echo "stage2" >> /usr/local/bin/fedora-postinstall-stage2
	chmod +x /usr/local/bin/fedora-postinstall-stage2

}

# Yes, I separated all the Firefox configurations into another function.
firefox_config() {

	# I don't know if the firefox prefs.js exists before first run (spoiler: it doesn't), so let's run firefox to generate it just in case.
	firefox &
	sleep 7

	set +e
	killall firefox
	set -e
	
	sleep 2
	
	ff_profile=$(find ~/.mozilla -iname prefs.js -execdir pwd \;)
	
	# Our configurations are going to go to user.js
	cd $ff_profile
	touch user.js
	
	# I like Fedora, but I do not want start.fedoraproject.org as my home page
	echo 'user_pref("browser.startup.homepage", "about:home");' >> user.js
	
	# UBlock Origin for the win
	cd /tmp
	wget -Oublock.xpi https://addons.mozilla.org/firefox/downloads/latest/ublock-origin/latest.xpi
	cp ublock.xpi ~/.mozilla/extensions/{ec8030f7-c20a-464f-9b0e-13a3a9e97384}/uBlock0@raymondhill.net.xpi
	cd -
	
	# Disable sponsored shortcuts in top sites
	echo 'user_pref("browser.newtabpage.activity-stream.showSponsored", false);' >> user.js
	echo 'user_pref("browser.newtabpage.activity-stream.showSponsoredTopSites", false);' >> user.js 

	# Clear DEFAULT top sites, just the default ones
	echo 'user_pref("browser.newtabpage.activity-stream.default.sites", "");' >> user.js

# Disable telemetry/crash reporting/related (borrowed from arkenfox user.js)
cat << EOF >> user.js
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("datareporting.healthreport.uploadEnabled", false);
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.enabled", false);
user_pref("toolkit.telemetry.server", "data:,");
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.newProfilePing.enabled", false);
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false);
user_pref("toolkit.telemetry.updatePing.enabled", false);
user_pref("toolkit.telemetry.bhrPing.enabled", false);
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false);
user_pref("toolkit.telemetry.coverage.opt-out", true);
user_pref("toolkit.coverage.opt-out", true);
user_pref("toolkit.coverage.endpoint.base", "");
user_pref("browser.ping-centre.telemetry", false);
user_pref("app.shield.optoutstudies.enabled", false);
user_pref("app.normandy.enabled", false);
user_pref("app.normandy.api_url", "");
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false);
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false);
user_pref("captivedetect.canonicalURL", "");
user_pref("network.captive-portal-service.enabled", false);
user_pref("network.connectivity-service.enabled", false);
EOF
	
	# Enable HTTPS-only mode
	echo 'user_pref("dom.security.https_only_mode", true);' >> user.js
	
	# Enable RFP
	echo 'user_pref("privacy.resistFingerprinting", true);' >> user.js

	# Delete default bookmarks we do not want
	cd ~/.mozilla/firefox/*.default-*/
	sqlite3 places.sqlite 'DELETE FROM moz_bookmarks WHERE id > 7;'
	cd -

	# No pinned sites please
	echo 'user_pref("browser.newtabpage.pinned", "[]");' >> user.js
	
	firefox -new-tab about:preferences#search >/dev/null & # This is the only way to get to DuckDuckGo as far as I can do it.
}

# Nautilus settings
nautilus_config() {
	gsettings set org.gnome.nautilus.preferences show-directory-item-counts 'local-only'
	gsettings set org.gnome.nautilus.preferences show-image-thumbnails 'local-only'
	gsettings set org.gnome.nautilus.preferences show-delete-permanently true
	
	set +e
	nautilus -q
	set -e
}

# Postinstall stage 1
stage1() {

	# Welcome message :)
	echo "Welcome to this Fedora postinstall script! This tool will take a while to run, so be prepared for that."
	sleep 2

	# When we are running as root with sudo, our memory of who we were before is erased ($USER and $HOME change). But we will need that info, so let's save it. sudo only preserves these environment variables because we use the -E flag later.
	export ORIGINAL_USER=$(whoami)
	export ORIGINAL_HOME=$HOME
	export NEW_HOSTNAME=${1:-fedora}
	
	# We are going to clone a few repos from the Internet, so let's make a directory for them.
	mkdir -p ~/.gitclone

	echo "Please enter your password to continue, as this script has to perform administrative tasks."
	# Everything we need to run as root is here, in stage1_root(). Thus there's no risk of running everything with sudo and having to enter a password several times because "dnf upgrade -y" took too long.
	# sudo doesn't know about stage1_root or any of the functions it calls, so we have to do things hackishly: I present this monstrosity of $(declare -f). Life would be much sweeter if we could write "sudo stage1_root"...
	sudo -E bash -c "$(declare -f stage2); $(declare -f install_helix); $(declare -f install_helix_unprivileged); $(declare -f install_nano); $(declare -f install_nvim); $(declare -f stage1_root); stage1_root"
	
	wallpaper=$(dialog --no-cancel --title "Select Wallpaper" --radiolist "Choose a default wallpaper to setup (you can change it to one of your choosing later):" 0 0 3 1 "Penguin" on 2 "Ice" off 3 "Pikachu" off --stdout)
	dock_options=$(dialog --no-cancel --title "Dock Options" --radiolist "Do you want to install a dock?" 0 0 3 1 "Yes (Recommended, unless you're familiar with GNOME)" on 2 "No thanks" off --stdout)

	# Install oh-my-zsh.
	sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
	
	# Enable the Starship prompt.
	echo 'eval "$(starship init zsh)"' >> ~/.zshrc
	
	# Install a few oh-my-zsh plugins.
	git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
	git clone https://github.com/zsh-users/zsh-syntax-highlighting ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
	
	# Enable the plugins (colored-man-pages is built-in)
	zsh -ic "omz plugin enable colored-man-pages" &
	sleep 2
	zsh -ic "omz plugin enable zsh-autosuggestions" &
	sleep 2
	zsh -ic "omz plugin enable zsh-syntax-highlighting" &
	
	sleep 4
	
	set +e
	killall -INT zsh
	set -e
	
	# Apply custom config to Firefox (the above function)
	firefox_config
	
	# Apply some nautilus preferences
	nautilus_config

	# Get ready to install some GNOME extensions...
	cd ~/.gitclone
	git clone https://github.com/brunelli/gnome-shell-extension-installer
	cd gnome-shell-extension-installer
	# Blur My Shell
	./gnome-shell-extension-installer 3193
	# Dash to Dock
	case $dock_options in 
		1) ./gnome-shell-extension-installer 307;;
		2) touch ~/.cache/postinstall-no-dash-to-dock;;
		*) echo "No dock selected";;
	esac
	# No overview at start-up
	./gnome-shell-extension-installer 4099
	# Tray Icons: Reloaded
	./gnome-shell-extension-installer 2890
	# Removable Drive Menu
	./gnome-shell-extension-installer 7
	# All these extensions are not recognized by GNOME right now, we have to log out and log back in to enable them/edit their configurations. This is why Stage 2 exists.
	# But rebooting at the end of Stage 1 is a way better option, since then all updates (including kernel updates) also take effect. And after a fresh install, there are a lot of updates.
	
	cd ~

	mkdir -p ~/Pictures/Wallpapers
	case $wallpaper in
		1) wget https://wallpaperset.com/w/full/0/3/e/219037.jpg -OPictures/Wallpapers/Background.jpg;; # Penguin
		2) wget https://cdn.pixabay.com/photo/2017/12/29/17/53/drift-ice-3048163_1280.jpg -OPictures/Wallpapers/Background.jpg;; # Ice
		3) wget https://wallpapercave.com/wp/wp1877515.jpg -OPictures/Wallpapers/Background.jpg;; # Pikachu
		*) :;;
	esac

	touch ~/.cache/fedora-postinstall-stage1-done
	
	mkdir -p ~/.config/autostart

# We want stage2 to autostart on next login, for simplicity
cat << EOF > ~/.config/autostart/fedora-postinstall.desktop
[Desktop Entry]
Version=1.0
StartupNotify=false
Type=Application
Terminal=false
Exec=fedora-postinstall-stage2
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=Fedora Postinstall
EOF

	chmod +x ~/.config/autostart/fedora-postinstall.desktop
	
	dialog --title "Done" --no-collapse --msgbox "Stage 1 of this postinstallation script is complete.\n When you exit this dialog, the computer will reboot.\n If you want to change the Firefox search engine from Google to something else, (like DuckDuckGo), now is the moment, before clicking OK.\n There is a Firefox window open for you to do that.\n" 0 0
	
	reboot
}

# Postinstall stage 2

stage2() {
	if [ -f ~/.cache/.fedora-postinstall-stage2-done ]; then
		echo "This script has already been run."
		exit 1
	fi

	# Hmmm... We don't need this anymore
	rm -f ~/.cache/fedora-postinstall-stage1-done
	
	sleep 2 # Ensure GNOME is ready

	# Enable the GNOME extensions we previously installed
	gnome-extensions enable blur-my-shell@aunetx
	gnome-extensions enable no-overview@fthx
	gnome-extensions enable drive-menu@gnome-shell-extensions.gcampax.github.com
	gnome-extensions enable trayIconsReloaded@selfmade.pl
	if ! [ -f ~/.cache/postinstall-no-dash-to-dock ]
	then
		gnome-extensions enable dash-to-dock@micxgx.gmail.com
	fi
	
	# Do everything related to GNOME appearance here
	
	# Restore Minimize and Maximize buttons in GNOME (they removed them by default for some reason)
	gsettings set org.gnome.desktop.wm.preferences button-layout ":minimize,maximize,close"

	# DARK MODE PLEASE
	gsettings set org.gnome.desktop.interface gtk-theme 'Adwaita-dark'
	gsettings set org.gnome.desktop.interface color-scheme 'prefer-dark'
	
	# Set wallpaper
	gsettings set org.gnome.desktop.background picture-uri "file:///$HOME/Pictures/Wallpapers/Background.jpg"
	gsettings set org.gnome.desktop.background picture-uri-dark "file:///$HOME/Pictures/Wallpapers/Background.jpg"
	
	touch ~/.cache/.fedora-postinstall-stage2-done
	
	rm -f ~/.config/autostart/fedora-postinstall.desktop
	if [ -f ~/.cache/postinstall-no-dash-to-dock ]
	then rm -f ~/.cache/postinstall-no-dash-to-dock
	fi
}

# This is actually the first part of the script to get executed, the end part.

if [ -f ~/.cache/.fedora-postinstall-stage2-done ]; then
	echo "This script has already been run."
else
	if [ -f ~/.cache/fedora-postinstall-stage1-done ]; then
		echo "Entering Stage 2..."
		stage2
	else
		echo "Entering Stage 1..."
		stage1 $1
	fi
fi
