#!/bin/bash

is_root() {
if [[ $EUID -ne 0 ]]; then
    printf "\n\n\n\e[41m  \e[0m Hi \e[1;37m$USER\e[0m, please run \e[1;37m</Gisto>\e[0m script as \e[1;37mroot\e[0m or with \e[1;37msudo\e[0m\n\e[41m\e[0m\n\n\n"
	exit 1
fi
}

greet () {
	printf "\n\n\n\e[44m  \e[0m Hi, This will install \e[1;37m</Gisto>\e[0m on your computer.\n\n\n"
}

remove_previous_version () {
    if [[ -f "/usr/bin/nw.pak" ]]; then
        /bin/rm -rf /usr/bin/gisto /usr/bin/nw.pak /usr/share/applications/gisto.desktop usr/share/menu/gisto /usr/share/pixmaps/gisto.png /usr/share/pixmaps/gisto.xpm > /dev/null 2>&1
    fi
}

check_dependencies_and_run () {

	printf "\n\n\n\e[43m  \e[0m Checking for dependencies.\n\n\n"

	for i in `find /bin /usr/bin -name "gconftool*"`; do
		if [[ ${i} =~ "gconf" ]]; then
			DEPS='OK'
		fi
	done;

	if [[ $DEPS = 'OK' ]]; then
	    remove_previous_version;
		install_gisto;
	else
		printf "\n\n\n\e[41m  \e[0m It seems you mising \e[1;37mgconf\e[0m. Please advise your package manager\n\n\n"
	fi
}

install_gisto () {
	printf "\e[42m  \e[0m It seems that all dependencies met, Install? [y/n]"
	read INST
	if [ $INST = 'y' -o $INST = 'Y' ]; then
        printf "\n\n\n\e[43m  \e[0m INSTALLING...\n\n\n"
        /bin/cp -rv gisto /opt
        /bin/cp -rv share /usr
        /bin/ln -s /opt/gisto/gisto /usr/bin/gisto

        paths=(
          "/lib/x86_64-linux-gnu/libudev.so.1" # Ubuntu, Xubuntu, Mint
          "/usr/lib64/libudev.so.1" # SUSE, Fedora
          "/usr/lib/libudev.so.1" # Arch, Fedora 32bit
          "/lib/i386-linux-gnu/libudev.so.1" # Ubuntu 32bit
        )

        for i in "${paths[@]}"
        do
          if [ -f $i ]
          then
            mkdir /opt/gisto/lib
            ln -sf "$i" /opt/gisto/lib/libudev.so.0
            break
          fi
        done

		printf "\n\n\n\e[42m  \e[0m Congrats! You can now find \e[1;37m</Gisto>\e[0m in your menu.\n\n\n"
	fi
}

is_root;

if [ "${1}" = "--uninstall" ]; then
	/bin/rm -rf /opt/gisto /usr/share/applications/gisto.desktop usr/share/menu/gisto /usr/bin/gisto > /dev/null 2>&1
	printf '\n\n\n\e[44m  \e[0m Congrats! Gisto removed from your machine.\n\n\n'
	exit 1
fi

# RUN ALL
greet;
check_dependencies_and_run;