#!/bin/bash
#
# ** header v3.0
# This file is a part of the CaosDB Project.
#
# Copyright (C) 2018 Research Group Biomedical Physics,
# Max-Planck-Institute for Dynamics and Self-Organization Göttingen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ** end header
#

DB_USER=caosdb
LOC_SUDOERS=/etc/sudoers.d
LOC_PREFIX=/usr/local/sbin
CMD_CHOWN=chown
SCRIPT_TMP=chown_script_template

# silent mode???
if [[ "$1" = "-s" ]]; then 
    SILENT="yes"
fi

# remove old files
if [ -r uninstall ]; then
    source uninstall > /dev/null
fi

# load config if existent
if [ -e CONFIG ]; then
    source CONFIG
fi

# check if all parameters are defined and valid
function check_parameters {
    if [ ! -e $LOC_DROPOFFBOX ]; then
        >&2 echo "DropOffBox $LOC_DROPOFFBOX does not exist."
        exit 11
    fi
    if [ ! -e $LOC_PREFIX ]; then
        >&2 echo "$LOC_PREFIX does not exist."
        exit 12
    fi
    if [ ! -e $LOC_SUDOERS ]; then
        >&2 echo "$LOC_SUDOERS does not exist."
        exit 13
    fi
    local ret=false
    getent passwd $DB_USER >/dev/null 2>&1 && ret=true
    if [[ $ret = false ]]; then
        >&2 echo "User $DB_USER does not exist."
        exit 14
    fi
}

# Echoes the absolute filename (in case a relative path is given).
# @return: absolute filename
function get_abs_filename {
    # $1 : relative filename
    if [ -d "$(dirname "$1")" ]; then
        echo "$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
    fi
}

# Promt for an input by the user (fancily).
# @arg $1: A description of the variable that the user has to specify.
# @arg $2: The name of the global variable the return value is to be stored in.
# @arg $3: Optional "-f". Indicates, that the user has to specify a file/folder. 
#          In this case, the tab completion is enabled, the existens of the
#          file/folder is tested, and relative paths are converted to absolute ones.
function prompt {
    if [[ "$SILENT" = "yes" ]]; then
        return 0
    fi
    local __ret=$2
    local default=$(eval echo \${$2})
    local new_val
    if [[ "$3" = "-f" ]]; then 
        local par="-e" 
    fi

	while [[ 0 = 0 ]]; do
        if [[ -z "$default" ]]; then
            PROMPT="Please insert $1: "
            read $par -p "${PROMPT}" new_val
        else 
            PROMPT="Please insert $1 or press ENTER for default [$default]: "
            read $par -p "${PROMPT}" new_val
            if [[ -z "$new_val" ]]; then                
                new_val=$default
                echo -en "\033[1A\033[2K"
                echo $PROMPT $new_val
            fi
        fi
        if [[ -z "$new_val" ]]; then
            # no value -> repeat while loop
            continue
        fi

        if [[ "$3" = "-f" ]]; then
            # check whether file exists
            if [ ! -e "$new_val" ]; then
                # file does not exist -> repeat
                echo "Directory/file does not exist. "
                continue
            fi
        fi

        # no problem occured -> leave while loop
        break
    done

    eval $__ret="'$new_val'"
}

# make sure this is root
[[ $(id -u) -eq 0 ]] || ! echo "You need to run this script as a root user." || exit 1

# make sure sudo is installed
sudo -v
if [[ ! $? -eq 0 ]]; then 
	>&2 echo -e "\ncommand 'sudo -v' failed. Did you install sudo?"
	exit 1
fi
    
# promt for dbuser
# default: caosdb
prompt "the unix user which who runs the caosdb server" DB_USER

# TODO
DB_GROUP=$DB_USER

# promt for sudoers.d
# default: /etc/sudoers.d/
prompt "the location of sudoers.d" LOC_SUDOERS -f
LOC_SUDOERS=$(get_abs_filename $LOC_SUDOERS)
LOC_SUDO_SCRIPT="${LOC_SUDOERS}/caosdb_chown_script"

# promt for prefix
# default: /usr/local/sbin/
prompt "the location of the script which is to be generated" LOC_PREFIX -f
LOC_PREFIX=$(get_abs_filename $LOC_PREFIX)
LOC_SCRIPT="${LOC_PREFIX}/caosdb_chown_dropoffbox"

check_parameters

# print info:
echo -e "\nDB_USER=$DB_USER"
echo "DB_GROUP=$DB_GROUP"
echo "LOC_SUDO_SCRIPT=$LOC_SUDO_SCRIPT"
echo "LOC_SCRIPT=$LOC_SCRIPT"
echo "CMD_CHOWN=$CMD_CHOWN"
echo -e "\n"

prompt "continue? [yes/no]" CONT

if [[ -n $CONT && "$CONT" != "yes" ]]; then
    echo "Installation aborted by the user."
    exit 0 
fi

echo '#!/bin/bash' > uninstall
echo '[[ $(id -u) -eq 0 ]] || ! echo "You need to run this script as a root user." || exit 1' >> uninstall
echo "rm $LOC_SCRIPT" >> uninstall 
echo "unlink ${LOC_SCRIPT##$LOC_PREFIX/}" >> uninstall
echo "rm $LOC_SUDO_SCRIPT" >> uninstall  
echo 'rm uninstall' >> uninstall
echo 'echo -e "\nDone."' >> uninstall
chmod ug+x uninstall

# configure script and store it
awk "BEGIN { 
  rep[\"__DB_USER__\"] = \"$DB_USER\"; 
  rep[\"__DB_GROUP__\"] = \"$DB_GROUP\"; 
  rep[\"__CMD_CHOWN__\"] = \"$CMD_CHOWN\"  
 }
 {
   for (key in rep) {
    gsub(key, rep[key])
   }
   print
 }" < $SCRIPT_TMP > $LOC_SCRIPT

# create symbolic link in working directory
ln -s $LOC_SCRIPT

# chown/chgrp to root
$CMD_CHOWN root:root $LOC_SCRIPT
# chmod 500 script
chmod 500 $LOC_SCRIPT

## configure sudo
echo -en "# Generated by caosdb install script. Do not edit!
# CONTACT: Timm Fitschen (timm.fitschen@ds.mpg.de)
# DATE: 2015-10-09
$DB_USER ALL = (root) NOPASSWD: $LOC_SCRIPT
" > $LOC_SUDO_SCRIPT
$CMD_CHOWN root:root $LOC_SUDO_SCRIPT
chmod 440 $LOC_SUDO_SCRIPT

# some tests
. test_functions
test1


echo -e "\nDone."


