#!/bin/bash
# VERSION: 2.0.0
function _press_any() {
    PA_PROMPT="\033[1;33m>>> Press any key to continue...\n\033[0m"
    if [ -n "$1" ]; then
        PA_PROMPT="\033[1;33m>>> $1...\n\033[0m"
    fi
    read -n1 -s -r -p "$(echo -e "$PA_PROMPT")" key
}
FLATPAK_SCOPE="user"
function add_flathub() {
	echo -e "\033[1;33m○ Adding flathub...\033[0m"
	flatpak --$FLATPAK_SCOPE remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
	flatpak --$FLATPAK_SCOPE remotes --show-details
	_press_any
}
function change_mirror() {
	echo -e "\033[1;33m○ Changing mirror url...\033[0m"
	flatpak --$FLATPAK_SCOPE remote-modify flathub --url=https://mirrors.ustc.edu.cn/flathub
	flatpak --$FLATPAK_SCOPE remotes --show-details
	_press_any
}
function add_xdg_data_dirs() {
	echo -e "\033[1;33m○ Adding XDG_DATA_DIRS to ~/.profile...\033[0m"
	XDGDATADIR="export XDG_DATA_DIRS=\"\$XDG_DATA_DIRS:/var/lib/flatpak/exports/share:\$HOME/.local/share/flatpak/exports/share\""
	if [ ! -f "$HOME/.profile" ]; then
		touch "$HOME/.profile"
	fi
	grep -qxF "$XDGDATADIR" "$HOME"/.profile || echo "$XDGDATADIR" | tee -a "$HOME"/.profile
	cat "$HOME/.profile" | grep "XDG_DATA_DIRS" 
	_press_any
}
function check_update() {
	echo -e "\033[1;33m○ Checking for update...\033[0m"
	flatpak --$FLATPAK_SCOPE update
	_press_any
}
function install_apps() {
	FLATAPPS_DEFAULT=(
		"io.github.jeffshee.Hidamari" " (Video Wallpaper)" OFF \
		"com.github.tchx84.Flatseal" " (Flatpak Manager)" ON \
		"io.github.flattool.Warehouse" " (Flatpak Manager)" ON \
		"io.github.giantpinkrobots.flatsweep" " (Flatpak Cleanup)" ON \
		"com.usebottles.bottles" " (Wine Bottles)" OFF \
		"me.iepure.devtoolbox" " (Dev)" ON \
		"org.localsend.localsend_app" " (LAN Share)" ON \
		"com.rafaelmardojai.Blanket" " (White Noise)" OFF \
		"org.chromium.Chromium" " (Chromium)" OFF \
		"io.github.ungoogled_software.ungoogled_chromium" " (Ungoogled Chromium)" OFF \
		"org.gnome.Brasero" " (Create ISO)" OFF \
		"org.kde.filelight" " (Disk Usage)" OFF \
		"org.fedoraproject.MediaWriter" " (Media Writer)" ON \
		"org.gimp.GIMP" " (Photo Edit)" OFF \
		"org.inkscape.Inkscape" " (Vector Edit)" OFF \
		"com.github.PintaProject.Pinta" " (Paint)" OFF \
		"org.kde.krita" " (Paint)" OFF \
		"org.freecad.FreeCAD" " (CAD)" OFF \
		"com.boxy_svg.BoxySVG" " (SVG)" ON \
		"fr.handbrake.ghb" " (Video Convert)" OFF \
		"org.bunkus.mkvtoolnix-gui" " (MKVToolNix GUI)" OFF \
		"info.smplayer.SMPlayer" " (VLC Video Player)" OFF \
		"org.videolan.VLC" " (Video Player)" OFF \
		"org.flameshot.Flameshot" " (Screenshot)" ON \
		"org.gnome.Snapshot" " (Capture Photo and Video)" ON \
		"org.kde.kcolorchooser" " (Color Choose)" OFF \
		"org.kde.kdenlive" " (Video Cut)" OFF \
		"com.obsproject.Studio" " (Screen Record)" OFF \
		"com.github.iwalton3.jellyfin-media-player" " (Jellyfin Client)" ON \
		"org.gnome.Decibels" " (Audio Player)" ON \
		"app.moosync.moosync" " (Music Player)" ON \
		"org.gnome.Rhythmbox3" " (Music Player)" OFF \
		"org.atheme.audacious" " (Music Player)" OFF \
		"org.audacityteam.Audacity" " (Audio Edit)" OFF \
		"org.gnome.EasyTAG" " (Audio Tags)" OFF \
		"app.drey.EarTag" " (Audio Tags)" OFF \
		"page.kramo.Sly" " (Simple Image Edit)" OFF \
		"org.kde.optiimage" " (Image Compress)" ON \
		"org.kde.subtitlecomposer" " (Subtitle Edit)" OFF \
		"net.meshlab.MeshLab" " (3D Viewer)" OFF \
		"com.vscodium.codium" " (Code Editor)" ON \
		"fr.free.qccrypt.Qccrypt" " (Encryption)" OFF \
		"org.dbgate.DbGate" " (Database)" ON \
		"org.filezillaproject.Filezilla" " (FTP)" ON \
		"garden.jamie.Morphosis" " (Doc Convert)" OFF \
		"br.eng.silas.qpdftools" " (PDF)" ON \
		"com.github.jeromerobert.pdfarranger" " (PDF)" ON \
		"org.kde.okular.kirigami" " (Doc Reader)" OFF \
		"org.onlyoffice.desktopeditors" " (Office)" ON \
		"org.bleachbit.BleachBit" " (Cleanup)" OFF \
		"io.github.flattool.Ignition" " (Autostart Manager)" OFF \
		"io.missioncenter.MissionCenter" " (Task Manager)" OFF \
		"org.virt_manager.virt-viewer" " (virt-viewer)" OFF \
		"me.hyliu.fluentreader" " (RSS)" OFF \
		"org.gnome.Papers" " (Doc Reader)" OFF \
		"com.github.themix_project.Oomox" " (Design Theme)" OFF \
		"io.otsaloma.nfoview" " (NFO Viewer)" OFF \
		"io.github.ronniedroid.concessio" " (chmod)" OFF \
		"net.supertuxkart.SuperTuxKart" " (Game)" OFF \
		"org.gnome.Chess" " (Game)" OFF \
		"org.kde.kmines" " (Game)" OFF \
		"org.luanti.luanti" "(Minetest)" OFF \
	)
	FLATAPPS=()
	FLATAPPS_SELOPT=$(whiptail --title "[Flatpak] Packages Selection" --yes-button "Continue" --no-button "Skip" --menu "Choose an action:" 16 60 8 "default" " (select recommanded only)" "none" " (select none)" 3>&1 1>&2 2>&3)
        exitstatus_sel=$?
        if [ $exitstatus_sel = 0 ]; then
		if [ "$FLATAPPS_SELOPT" = "none" ]; then
			for i in "${FLATAPPS_DEFAULT[@]}"; do
				if [ "$i" = "ON" ]; then
					FLATAPPS+=("OFF")
				else
					FLATAPPS+=("$i")
				fi
			done
		else
			FLATAPPS+=("${FLATAPPS_DEFAULT[@]}")
		fi
	fi
	echo -e "\033[1;33m○ Installing apps...\033[0m"
	FOSS=$(whiptail --title "[Flatpak] Packages" --checklist "Free Open Source Packages" 16 60 8 "${FLATAPPS[@]}" 3>&1 1>&2 2>&3)
	exitstatus_foss=$?
	if [ $exitstatus_foss = 0 ]; then
		FOSSS="${FOSS[@]}"
		FOSSA="${FOSSS//\"/}"
		FLAT_INSTALL_METHOD=$(whiptail --title "[Flatpak] Install Method" --yes-button "Continue" --no-button "Skip" --menu "How to install these Flatpak packages: $FOSSA" 16 60 8 \
			"Joined" "" \
			"Seprated" "" \
			3>&1 1>&2 2>&3)
		exitstatus_flat_method=$?
		if [ $exitstatus_flat_method = 0 ]; then
			echo -e "\033[1;33m○ Installing \033[1;32m$FOSSA\033[0m"
			if [ "$FLAT_INSTALL_METHOD" = "Joined" ]; then
				echo -e "\033[1;33m○ Running \033[1;32mflatpak --$FLATPAK_SCOPE install $FOSSA\033[0m"
				flatpak --$FLATPAK_SCOPE install $FOSSA
			elif [ "$FLAT_INSTALL_METHOD" = "Seprated" ]; then
				IFS=' ' read -ra FOSSARRAY <<< "$FOSS"
				FOSSARRAY_COUNT="${#FOSSARRAY[@]}"
				for ((IDX = 0; IDX < FOSSARRAY_COUNT; IDX++)); do
					pkg="${FOSSARRAY[IDX]}"
					pkg="${pkg//\"/}"
					IDX_PLUS=$((IDX + 1))
					echo -e "\033[1;33m○ ($IDX_PLUS/$FOSSARRAY_COUNT) Running \033[1;32mflatpak --$FLATPAK_SCOPE install $pkg\033[0m"
					flatpak --$FLATPAK_SCOPE install "$pkg"
				done
				unset IFS
			fi
		fi
		_press_any
	fi
}
function sync_lan_data() {
	if (whiptail --title "[Flatpak] Sync LAN Data" --yes-button "Sync" --no-button "Skip" --yesno "" 15 60) then
		echo -e "\033[1;33m○ Syncing data via LAN...\033[0m"
		MIRRORLIST=("com.vscodium.codium")
		MIRRORDOMAIN="$(whiptail --title "Mirror From" --inputbox "For example: Cube.local" 15 60 "Cube.local" 3>&1 1>&2 2>&3)"
		for MITEM in "${MIRRORLIST[@]}"; do
			echo -e "\033[1;33m○ Syncing $MITEM...\033[0m"
			if [ ! -d "$HOME/.var/app/$MITEM" ]; then
				mkdir -p "$HOME/.var/app/$MITEM/"
			fi
			echo -e "\033[1;33mrsync -ahP --verbose --info=progress2 --stats --iconv=UTF-8 --delete ezra@$MIRRORDOMAIN:/home/ezra/.var/app/$MITEM/ ~/.var/app/$MITEM/\033[0m"
			rsync -ahP --verbose --info=progress2 --stats --iconv=UTF-8 --delete ezra@$MIRRORDOMAIN:/home/ezra/.var/app/$MITEM/ ~/.var/app/$MITEM/
		done
		#R_HOSTNAME="$(hostname)"
		#R_HOSTNAME="${R_HOSTNAME//[$'\t\r\n ']}"
		#LOCALSEND_CFG="$HOME/.var/app/org.localsend.localsend_app/data/localsend_app/shared_preferences.json"
		#if [ -f "$LOCALSEND_CFG" ]; then
		#	sed -i "s/Cube/$R_HOSTNAME/g" "$LOCALSEND_CFG"
		#	nano "$LOCALSEND_CFG"
		#fi
		_press_any
	fi
}
function remove_unused() {
	echo -e "\033[1;33m○ Removing unused...\033[0m"
	flatpak --$FLATPAK_SCOPE remove --unused
	_press_any
}

ACTION=$(whiptail --title "[Flatpak] Action" --menu "Choose an action to perform:" 16 60 8 \
	"0" "ALL" \
	"1" "Add Flathub" \
	"2" "Change Mirror" \
	"3" "Add XDG_DATA_DIRS" \
	"4" "Check Update" \
	"5" "Install Apps" \
	"6" "Sync LAN Data" \
	"7" "Remove Unused" \
	3>&1 1>&2 2>&3)
exitstatus_action=$?
if [ $exitstatus_action = 0 ]; then
        FLATPAK_SCOPE_OPT=$(whiptail --title "[Flatpak] Scope" --yes-button "Continue" --no-button "Skip" --menu "Choose the scope:" 16 60 8 "user" "" "system" "" 3>&1 1>&2 2>&3)
        exitstatus_fp=$?
        if [ $exitstatus_fp = 0 ]; then
		FLATPAK_SCOPE="$FLATPAK_SCOPE_OPT"
		echo -e "\033[1;32m=> \033[1;33mFlatpak scope: $FLATPAK_SCOPE...\033[0m"
	else
		echo -e "\033[1;32m=> \033[1;31mUser canceled...\033[0m"
		exit 1
        fi
	if [ "$ACTION" = "1" ]; then
		add_flathub
	elif [ "$ACTION" = "2" ]; then
		change_mirror
	elif [ "$ACTION" = "3" ]; then
		add_xdg_data_dirs
	elif [ "$ACTION" = "4" ]; then
		check_update
	elif [ "$ACTION" = "5" ]; then
		install_apps
	elif [ "$ACTION" = "6" ]; then
		sync_lan_data
	elif [ "$ACTION" = "7" ]; then
		remove_unused
	elif [ "$ACTION" = "0" ]; then
		add_flathub
		change_mirror
		add_xdg_data_dirs
		check_update
		install_apps
		sync_lan_data
		remove_unused
	fi
fi

