#!/bin/bash
################################################################################
#    HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
################################################################################

INSTALL_DIR=/opt/HPCCSystems
CONFIG_DIR=/etc/HPCCSystems
ENV_XML_FILE=environment.xml
ENV_CONF_FILE=environment.conf
PID_DIR=/var/run/HPCCSystems
LOCK_DIR=/var/lock/HPCCSystems
LOG_DIR=/var/log/HPCCSystems
INIT_PATH=/etc/init.d


source ${INSTALL_DIR}/etc/init.d/hpcc_common
source ${INSTALL_DIR}/etc/init.d/init-functions

installConfs ()
{
    fileName=$1
    configPath=$2
    mkdir -p ${configPath}
    mkdir -p ${configPath}/rpmnew

    printf "Installing %-44s ..." "${fileName}"

    if [ ! -e ${configPath}/${fileName} ]; then
        # Always install new files without comment
        cp -f ${INSTALL_DIR}/${configPath}/rpmnew/${fileName} ${configPath}/${fileName}
        cp -f ${INSTALL_DIR}/${configPath}/rpmnew/${fileName} ${configPath}/rpmnew/${fileName}
        log_success_msg
    elif [ -e ${configPath}/rpmnew/${fileName} ] && ! `diff -q ${configPath}/rpmnew/${fileName} ${INSTALL_DIR}/${configPath}/rpmnew/${fileName} >/dev/null` ; then
        # There are changes in the default config since last installed
        if ! `diff -q ${configPath}/rpmnew/${fileName} ${configPath}/${fileName} >/dev/null` ; then
            # User has made their own changes too, so don't overwrite
            log_failure_msg "Not overwriting modified configuration file ${fileName}"
        else
            # User has NOT made their own changes - ok to update
            cp -f ${INSTALL_DIR}/${configPath}/rpmnew/${fileName} ${configPath}/${fileName}
            cp -f ${INSTALL_DIR}/${configPath}/rpmnew/${fileName} ${configPath}/rpmnew/${fileName}
            log_success_msg "Updated configuration file ${fileName}"
        fi
    else
        log_success_msg "No changes to configuration file ${fileName}"
    fi
}


installFile ()
{
    fileNameFrom=$1
    fileNameTo=$2
    symlink=$3
    createDir=$4
    option="-f"
    if [ ${symlink} != 0 ];then
        option="-sf"
    fi

    if [ ! -z "${createDir}" ]; then
        if [ ! -d ${createDir} ];then
            mkdir -p ${createDir}
        fi
    fi

    cp ${option} ${fileNameFrom} ${fileNameTo} 2> /dev/null

    printf "Installing %-44s ..." "${fileNameTo}"
    if [ -L ${fileNameTo} ]; then
        log_success_msg
    elif [ -e ${fileNameTo} ] && [ ! -L ${fileNameTo} ] ; then
        log_success_msg
    else
        log_failure_msg
    fi
}


fileCheck ()
{
    inFile=$1
    echo -n "Checking SSH Key for user $user ..."
    if [ ! -e $inFile ]; then
        echo "Fail"
        echo "Bad File name"
    fi

    while read line
    do
        first=$( echo $line | awk '{ print $1 }' )
        second=$( echo $line | awk '{ print $2 }' )

        passValue=0
        if [ -f $first ] && [ -f $second ]; then
            newSum=$( md5sum $second )
            if [ ${newSum} -eq ${first} ]; then
                sc=0
            else
                sc=1
            fi
        else
            sc=0
        fi

        if [ "$sc" -gt 0 ]; then
           passValue=$(( ${passValue} + 1 )) 
        fi  
    done < ${inFile}

    if [ ${passValue} -lt 3 ]; then
        __fileCheck=0
        echo "Fail"
        echo "*** Security Alert ***"
        echo "You are using a publicly available default key."
        echo "Please run 'sudo ${path}/sbin/update-keys -g' to generate and deploy secure keys to"
        echo "all nodes declared in your environment.xml"
        echo "***  Security Alert  ***"
    else
        __fileCheck=1
        echo "OK"
    fi

}
#---------------------------------------------------------------------
# Main code
#---------------------------------------------------------------------
SECTION=${SECTION:-DEFAULT}

confToUse="${INSTALL_DIR}${CONFIG_DIR}/${ENV_CONF_FILE}"

if [ -d ${CONFIG_DIR} ]; then
    if [ -f ${CONFIG_DIR}/installed ] ; then
        exit 0
    fi
    if [ -e ${CONFIG_DIR}/${ENV_CONF_FILE} ]; then
        confToUse="${CONFIG_DIR}/${ENV_CONF_FILE}"
    fi
fi

# Reading and processing conf file
cfg.parser ${confToUse}
cfg.section.${SECTION}

if [ ${DEBUG:-NO_DEBUG} != "NO_DEBUG" ]; then
    echo "\$runtime=$runtime"
    echo "\$path=$path"
    echo "\$configs=$configs"
    echo "\$configsbackup=$configsbackup"
    echo "\$user=$user"
    echo "\$lock=$lock"
    echo "\$pid=$pid"
    echo "\$log=$log"
    echo "\$environment=$environment"
    echo "\$interface=$interface"
    echo "\$sourcedir=$sourcedir"
    echo
fi

#Checking if user exists and if doesn't then creating one
useradd_d=$(echo "[DEFAULTLINUX]" > /tmp/tmp_defaultuser.conf;useradd -D >> /tmp/tmp_defaultuser.conf)
cfg.parser /tmp/tmp_defaultuser.conf
cfg.section.DEFAULTLINUX

if [ "$HOME" != "$home" ]; then
    echo "Linux Default home directory is different from HPCC default."
    echo "Will continue to work with Linux Default $HOME....."
    homePath=$HOME/$user
fi

initPath="$path/etc/init.d"
homePath=$HOME/$user
binPath="$path/bin"

add_user $user $group $homePath || exit 1

# If user already exists get the home directory
homePath=$(cat /etc/passwd | grep -e "^${user}:" | cut -d':' -f6)
homeBase=$(dirname $homePath)
echo ""

# installing files
installConfs "environment.conf" $configs/ 1 || exit 1
installConfs "environment.xml" $configs/  1 || exit 1
installConfs "genenvrules.conf" $configs/ 1 || exit 1

installFile "$path${CONFIG_DIR}/version" "${CONFIG_DIR}/version" 1 || exit 1
installFile "$initPath/dafilesrv" "/etc/init.d/dafilesrv" 1 || exit 1
installFile "$binPath/dfuplus" "/usr/bin/dfuplus" 1 || exit 1
installFile "$binPath/ecl" "/usr/bin/ecl" 1 || exit 1
installFile "$binPath/eclcc" "/usr/bin/eclcc" 1 || exit 1
installFile "$binPath/eclplus" "/usr/bin/eclplus" 1 || exit 1
installFile "$binPath/wuget" "/usr/bin/wuget" 1 || exit 1
installFile "$configs/$environment" "$sourcedir/$environment" 0 "$sourcedir"

installFile "$path${CONFIG_DIR}/configmgr/configmgr.conf"  \
     "${CONFIG_DIR}/configmgr/" 0 "${CONFIG_DIR}/configmgr" || exit 1
installFile "$path${CONFIG_DIR}/configmgr/esp.xml" "${CONFIG_DIR}/configmgr/" 0 || exit 1
installFile "$path${CONFIG_DIR}/config2mgr/esp.xml"  \
     "${CONFIG_DIR}/config2mgr/" 0 "${CONFIG_DIR}/config2mgr" || exit 1

# locate sub install files.
if [ -d ${INSTALL_DIR}/etc/init.d/install ]; then
    for subInstall in $(ls ${INSTALL_DIR}/etc/init.d/install); do
        source ${INSTALL_DIR}/etc/init.d/install/${subInstall}
    done
fi

# bash completion
if [ -d ${INSTALL_DIR}/etc/bash_completion.d ] && [ -d /etc/bash_completion.d ]; then
    for subInstall in $(ls ${INSTALL_DIR}/etc/bash_completion.d | grep -v dpkg-tmp); do
        installFile ${INSTALL_DIR}/etc/bash_completion.d/$subInstall /etc/bash_completion.d/$subInstall 1 || exit 1
    done
fi

# SSH config dir
if [ ! -d ${homePath}/.ssh ]; then
    mkdir -p ${homePath}/.ssh
fi

totalFiles=$(ls -l ${homePath}/.ssh | head -n 1 | awk '{ print $2 }' )
if [ -d $homePath/.ssh ] && [ "$totalFiles" -le 3 ]; then
    installFile "${path}/etc/sshkey/.ssh.md5" "${homePath}/.ssh.md5" 0 || exit 1
    fileCheck "${homePath}/.ssh.md5"

    if [ ${__fileCheck} -eq 0 ]; then
        installFile "${path}/etc/sshkey/.ssh/authorized_keys" "${homePath}/.ssh/authorized_keys" 0 || exit 1
        installFile "${path}/etc/sshkey/.ssh/id_rsa" "${homePath}/.ssh/id_rsa" 0 || exit 1
        installFile "${path}/etc/sshkey/.ssh/id_rsa.pub" "${homePath}/.ssh/id_rsa.pub" 0 || exit 1
    fi
else
    printf "SSH keys are already installed for user %-15s ..." "$user"
    log_success_msg
fi

## for now turn off certificate logic if we're switching to setupPKI and distributePKI

#if [ ! -d ${homePath}/certificate ]; then
#    mkdir -p ${homePath}/certificate
#fi
#
#if [ ! -e ${homePath}/certificate/key.pem ]; then
#    ssh-keygen -t rsa -N '' -f ${homePath}/certificate/key.pem \
#        1>/dev/null 2>&1
#    openssl rsa -in ${homePath}/certificate/key.pem -pubout \
#        -out ${homePath}/certificate/public.key.pem 
#    chmod 0644 ${homePath}/certificate/public.key.pem
#    rm -f ${homePath}/certificate/key.pem.pub
#    printf "RSA key installed for user %-28s ..." "$user"
#    log_success_msg
#else
#    printf "RSA keys are already installed for user %-15s ..." "$user"
#    log_success_msg
#fi
#
#if [ ! -e ${homePath}/certificate/certificate.pem ]; then
#    openssl req -new -key ${homePath}/certificate/key.pem -keyform PEM -x509 \
#        -days 365 -out ${homePath}/certificate/certificate.pem \
#        -batch 1>/dev/null 2>&1
#    printf "Self Signed Certificate installed for user %-12s ..." "$user"
#    log_success_msg
#else
#    printf "Self Signed Certificate already installed for %-9s ..." "$user"
#    log_success_msg
#fi

# Added code to change environment.conf file user home directory location for key generation
if [ "$homeBase" != "$home" ]; then
    sed -e "s;^[[:space:]]*home[[:space:]]*=.*$;home=$homeBase;" ${CONFIG_DIR}/${ENV_CONF_FILE} > temp.conf
    mv temp.conf ${CONFIG_DIR}/${ENV_CONF_FILE}
fi



# Setting up values for /etc/sudoers and /etc/security/limits.conf files
${path}/sbin/add_conf_settings.sh

groupNum=`grep "^${user}:" /etc/passwd  | cut -d ':' -f 4`
group=`grep -w ${groupNum} /etc/group | cut -d ':' -f 1`

#Assigning correct permission for /User/hpcc
chmod 700 ${homePath}/.ssh
[ -e ${homePath}/.ssh/id_rsa.pub ] && chmod 600 ${homePath}/.ssh/id_rsa.pub
chown -R $user:$group ${homePath}

$path/sbin/add_conf_settings.sh

confPath=${path}${CONFIG_DIR}

if [ -d ${confPath} ]; then
    for i in $(find $confPath)
    do 
        if [ -d $confPath/$i ]; then
            if [ -d $configs/$i ]; then
                for infile in $(find $confPath/$i)
                do
                    cp $confPath/$i/$infile $configs/$i/$infile
                done
            else
                mkdir $configs/$i
                for infile in $(find $confPath/$i)
                do 
                    cp "$confPath/$i/$infile" "$configs/$i/$infile"
                done
            fi
        fi
    done
fi

chown root:$group ${configs}
chown -R $user:$group ${configs}/*
chmod 775 ${configs}

which_init_system=$(ps --no-headers -o comm 1)
if [ "${which_init_system}" == "systemd" ]; then
    systemctl daemon-reload
fi

createRuntime
[ -e  ${LOG_DIR}/hpcc-init.debug ] && chown ${user}:${user} ${LOG_DIR}/hpcc-init.debug

exit 0
