#!/bin/bash
## zramraid-install (Default for Debian & Ubuntu)
## (c) author's idea and realization: Kleemov A. & Koshuba V.
## script author: Koshuba V - stvixfree@gmail.com
## version = 26.06.18
## License: GPLv3
option=$1;
rdate=$(date +%c);
reports=();
getpkg=( "jq" "mdadm" "lsb-release" );
test_module=$(find /lib/modules/$kernel_version -name '*.ko'|grep zram|wc -m);
log="/var/log/syslog";
eval kernel_version="(" $(uname -r|sed 's/\./ /g') ")";
deb_release=""
## functions & operations
operation_install=( "clear" "testId" "checkDep" "checkMod" "install" "printInfo" );
operation_uninstall=( "clear" "testId" "checkDep" "checkMod" "uninstall" "printInfo" );
operation_help=( "clear" "printInfo" );
execute_func=();

## -@F logic executor
function eXlogic() {
lEnd=1;
if [[ ${#iFs[@]} -eq 0 ]]||[[ ${#iFs[@]} != ${#logic[@]} ]]
    then echo "exit";
         exit 0;
fi

local exfunc=();
for ((lg_index=0; lg_index != ${#iFs[@]}; lg_index++))
 do
    ## !! debug operation...
    #echo "eXlogic = execution: function ${iFs[$lg_index]} : index=$lg_index";
    local lg=$(echo $((${iFs[$lg_index]})) );
    local exfunc=( ${logic[$lg_index]} );
    local runfunc=$(echo ${exfunc[$lg]}| sed 's/\"//g');
    $runfunc;
    if [[ $lEnd == 0 ]] 
        then lg_index=$((${#iFs[@]}-1)); 
    fi
done
iFs=();
logic=();
value_in="";
}


##--@F write log events
function writeToLog() {
for ((rpt_index=0; rpt_index != ${#reports[@]}; rpt_index++))
do
    echo  "$rdate zramraid install  message: ${reports[$rpt_index]}">>$log;
done
}

function printInfo() {
value_in="$option";
iFs=(   "$(echo -n $value_in|wc -m) == 0"
        "$(echo -n $value_in|sed 's/--help//g'|wc -m) == 0" 
        "$(echo -n ${#reports[@]}) == 0" );

logic=( '"" "pIhelp"'
        '"" "pIhelp"'
        '"pIdf" "pIhelp"' );

function pIhelp() {
    lEnd=0;
    clear
    echo
    echo -e "install: zramraid-install --install";
    echo -e "uninstall: zramraid-install --uninstall";
    echo -e "help: zramraid-install --help";
    exit 0;
}

## default function last eXlogic..
function pIdf() {
    for ((rpt_index=0; rpt_index != ${#reports[@]}; rpt_index++))
        do
    echo   "${reports[$rpt_index]}";
    done
    exit 0;
    }
eXlogic;
}

##--@F make all errors
function makeErr() {
 reports[${#reports[@]}]="Operation not succeded";
 printInfo;
 writeToLog;
 exit 0;
}


##@F-tests
function checkMod() {
    if (( "${kernel_version[0]}" >= "3" ))
	then
	    if (( ! "${kernel_version[1]}" >= "14" ))
		then 
	    reports[${#reports[@]}]="Sorry Kernel version < 3.14.x";
	    makeErr;
		exit 0;
	    fi
	else
	    reports[${#reports[@]}]="Sorry Kernel version < 3.x";
	    makeErr;
		exit 0;
    fi
# test module zram
if [ $test_module == 0 ] 
    then
    reports[${#reports[@]}]="The current kernel does not find zram module";
    makeErr;
fi

}

##--@F Check the program dependency
function checkDep() {
if [[ ! $(apt-cache policy ${getpkg[@]} | grep status|wc -l) = $(echo -e ${#getpkg[@]}) ]];
    then apt-get install $(echo ${getpkg[@]});
fi

for ((ipkg=0; ipkg != ${#getpkg[@]}; ipkg++))
 do
    if [ ! "$(apt-cache policy ${getpkg[$ipkg]} | grep status)" ]
    then
    ## lang messages if yes then lang else us...
    reports[${#reports[@]}]="Do not set ${getpkg[$ipkg]} package";
    makeErr;
fi
done
local lsbtools=$(whereis -b lsb_release|awk '/^lsb_release:/{print $2}');
deb_release=$( $lsbtools -r|awk '/^Release:/{print $2}'|sed 's/\./ /g'|awk '{print$1}' );
}


function install() {
if [ ! -d "/etc/zramraid" ]
    then
	mkdir -p /etc/zramraid;
fi
cp -f $PWD/etc/zramraid/messages.dat /etc/zramraid/messages.dat;
cp -f $PWD/etc/zramraid/zramraid-config /etc/zramraid/zramraid-config;
cp -f $PWD/etc/zramraid/zramraid-maker /etc/zramraid/zramraid-maker;
cp -f $PWD/etc/init.d/zramraid-manager /etc/init.d/zramraid-manager;
cp -f $PWD/etc/default/zramraid /etc/default/zramraid;
ln -s /etc/zramraid/zramraid-maker /usr/local/bin/zramraid-maker;
ln -s /etc/zramraid/zramraid-config /usr/local/bin/zramraid-config;

if [[ $deb_release < 8 ]]; 
     then
	update-rc.d -n zramraid-manager defaults;
     else
	cp -f $PWD/lib/systemd/system/zramraid.service /lib/systemd/system/zramraid.service;
	/bin/systemctl enable zramraid.service;
	if [ -f "/lib/systemd/system/libvirt-guests.service" ];
	    then
		if [ $(cat /lib/systemd/system/libvirt-guests.service|grep zramraid|wc -m ) = 0 ];
		    then
			sed -i '/Requires=virt-guest-shutdown.target/a \'"Requires=zramraid.service" /lib/systemd/system/libvirt-guests.service;
		fi
	fi
fi
reports[${#reports[@]}]="zramraid install susseful";
reports[${#reports[@]}]="please setup config for autostart from boot: /etc/default/zramraid.";
writeToLog;
printInfo;
}

function uninstall() {

function zrDel() {
if [[ $deb_release < 8 ]]; 
     then
	/etc/init.d/zramraid-manager stop;
	update-rc.d -n zramraid-manager remove;
     else
    /bin/systemctl stop zramraid.service;
    /bin/systemctl disable zramraid.service;
    rm /lib/systemd/system/zramraid.service;
    if [ -f "/lib/systemd/system/libvirt-guests.service" ];
	    then
		if [ ! $(cat /lib/systemd/system/libvirt-guests.service|grep zramraid|wc -m ) = 0 ];
		    then
			sed -i -e '/'"Requires=zramraid.service"'/d' /lib/systemd/system/libvirt-guests.service;
		fi
	fi
fi
	rm -f /usr/local/bin/zramraid-maker;
	rm -f /usr/local/bin/zramraid-config;
	rm -f /etc/zramraid/messages.dat;
	rm -f /etc/zramraid/zramraid-config;
	rm -f /etc/zramraid/zramraid-maker;
	rm -f /etc/init.d/zramraid-manager;
	rm -f /etc/default/zramraid;
    }

if [ ! -f "/etc/zramraid/zramraid.conf" ]
    then
    zrDel;
    rm -rf /etc/zramraid;
    else
    zrDel;
fi
reports[${#reports[@]}]="zramraid uninstall susseful";
writeToLog;
printInfo;

}

##--@F step operation
function testId() {
if (( ! $(id|grep "root"|wc -m) ))
        then
        reports=(); 
        reports[${#reports[@]}]="It is only available with root privileges";
        makeErr;
fi
}


##--@F executor
function executor() {
if [[ ${#execute_func[@]} -eq 0 ]] 
    then echo "exit";
         exit 0; 
fi
for ((ex_index=0; ex_index != ${#execute_func[@]}; ex_index++))
 do
    ## !! debug operation...
    ##echo "execution: function ${execute_func[ex_index]}"
 ${execute_func[ex_index]};
done
}

##- Begin zramraid
case "$option" in

## install zramraid
"--install" | "--install" )
execute_func=( ${operation_install[@]} );
executor;
exit 0
;;

## uninstall zramraid
"--uninstall" | "--uninstall" )
execute_func=( ${operation_uninstall[@]} );
executor;
exit 0
;;

## help
"--help" | "--help" )
execute_func=( ${operation_help[@]} );
executor;
exit 0
;;

* )
# selecting defaults.
execute_func=( ${operation_help[@]} );
executor;
exit 1
;;
esac
