#!/usr/bin/bash

### INSTALL / REMOVE SCRIPT ###

# Test if running as root
if [[ "$EUID" -ne 0 ]]; then
	printf "\n\e[31mMust run as root , use: \e[32msudo install.fortune-dhammapda.sh\e[0m\n\n"
	exit 1
fi

# Usage
USAGE="
Arguements:
	-i || install 	- Install fortune-dhammapada
	-u || uninstall	- Uninstall fortune-dhammapada
"

# Initialize variables
FORTUNE=$(which fortune 2>&1) || { printf "\n\e[31mInstall fortune then re-run install.sh\n\n\e[0mExample:\n\tsudo apt install fortune-mod\n\tsudo dnf install fortune-mod\n\tsudo pacman -S fortune-mod\n\n" ; exit 1 ; }

SOURCE_FILES="usr/share/games/fortune"

STRFILE=$(which strfile)

#Set destination for fortune files
DEST_FILES="$(fortune -f 2>&1 | head -n 1 | awk '{print $NF}')"

if [[ "$#" -gt "1" ]]; then printf "%s\n" "$USAGE"; exit 1; fi

# Function to install fortunes
installtrans () {
	cp -v "$SOURCE_FILES"/* "$DEST_FILES"/
	for file in "$DEST_FILES"/dhammapada*; do
		"$STRFILE" "$file" "$file".dat
	done
}

case "$1" in
	-i | install )
		if [[ -f "$DEST_FILES"/dhammapada ]] ; then 
			printf "\n\e[fortune-dhammapada already installed\e[0m\n\n"
			exit 1
		else
			installtrans
		fi
		gzip -c man/fortune-dhammapada.1 > /usr/share/man/man1/fortune-dhammapada.1.gz
		printf "\n\e[32mInstall successful\e[0m\n\n"
		exit 0
		;;
	-u | uninstall )
		if [[ ! -f "$DEST_FILES"/dhammapada ]] ; then
			printf "\n\e[32mfortuen-dhammapada not installed\e[0m\n\n"
			exit 1
		fi
		rm -v "$DEST_FILES"/dhammapada*
		rm -v /usr/share/man/man1/fortune-dhammapada.1.gz
		printf "\n\e[32mRemoval successful\e[0m\n\n"
		if [[ -n "$FORTUNE" ]]; then printf "\e[33mRemove fortune if you wish\e[0m\n\n"; fi
		exit 0
		;;
	*)
	printf "%s\n" "$USAGE"
	exit 1
	;;
esac
