#!/bin/bash

set -o noclobber


#The introduction
echo "Hello, and welcome to the Flatpak App Backup Script!"

echo "This is Version 0.1"

echo "It only works if you have Flatpak installed and have added all remotes from which you have installed flatpaks. It only works for system-wide installs."

echo "You can either save your selection of installed flatpaks as a file (backup), or install all the flatpak apps listed in such a file (restore)."

echo "If you restore, you'll have to answer the questions flatpak asks during the installation process yourself."

echo ""

#Deciding on whether to backup or restore from a backup
echo "Type 'b' to backup, or 'r' to restore from a backup, and confirm with Enter/Return:"
echo ""
read typeoftask
echo ""

# The backup subroutine
if [ $typeoftask = 'b' ]; then
	echo "You have chosen to backup your flatpak app selection."
	echo ""
	
	# Asking for a backup file name
	echo "Type a name for a backup file. It has to be a file that doesn't exist yet in this directory."
	echo ""
	read bfilename
	
	# Creating a temporary file listing installed flatpaks
	ls /var/lib/flatpak/app/ > apurelytemporaryfile.txt
	
	# Changing the line breaks in the list to blank spaces
	tr '\n' ' ' < apurelytemporaryfile.txt >  $bfilename
	
	# Deleting the temporary file
	rm apurelytemporaryfile.txt
	
	echo ""
	echo "If things worked as expected, your file" $bfilename "has been created."
	
	# The restore subroutine
    elif [ $typeoftask = 'r' ]; then
	    echo "You have chosen to restore your flatpak app selection."
	    echo ""
	    # Asking for a file from which to restore
	    echo "Type the name of a file from which you want to restore. It must exist in this directory."
	    echo ""
	    read rfilename
	    
	    echo ""
	    echo $rfilename
	    
	    # Trying to get flatpak to install the apps listed in the restore file
	    flatpak install $(< $rfilename)
	    echo ""
	    echo "If everything worked out, all your flatpak apps should have been installed now."
	        
#The wrong input subroutine
else
    echo "You have to type either 'b' or 'r'. Since you didn't, the script ends now"
fi

