#!/bin/bash

# Copyright (c) Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2018 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

function getRPM(){
PARAM="$1"
RESULT=""
mkfifo /usr/share/lve/da_lsapi/da_install_lsapi
ls -1 /usr/share/lve/da_lsapi/$PARAM* 2>/dev/null 1> /usr/share/lve/da_lsapi/da_install_lsapi &
while read file_nm
do
  RESULT=$(echo "$file_nm" | grep $PARAM)
  if [ -n "$RESULT" ];then
     break
  fi
done <  /usr/share/lve/da_lsapi/da_install_lsapi
rm /usr/share/lve/da_lsapi/da_install_lsapi
echo "$RESULT"
}

SOCKPATH="/var/run/mod_lsapi"

REPO="$1"
VER="$2"

if [ -n "$REPO" -a -n "$VER" ];then 

yum install -y yum-utils
REPOSIT=""
if [ "$REPO" == "beta" ];then
REPOSIT="--enablerepo=cloudlinux-updates-testing"
fi

RESULT=""
RESULT_DEVEL=""
mkdir -p /usr/share/lve/da_lsapi/

RESULT=$(getRPM liblsapi-"$VER")

RESULT_DEVEL=$(getRPM liblsapi-devel-"$VER")

if [ -z "$RESULT" ]; then
    pushd /usr/share/lve/da_lsapi/
    yumdownloader liblsapi-"$VER"* --disableexcludes=all --downloaddir=/usr/share/lve/da_lsapi/ "$REPOSIT"
    popd
fi

if [ -z "$RESULT_DEVEL" ]; then
    pushd /usr/share/lve/da_lsapi/
    yumdownloader liblsapi-devel-"$VER"* --disableexcludes=all --downloaddir=/usr/share/lve/da_lsapi/ "$REPOSIT"
    popd
fi

RESULT=$(getRPM liblsapi-"$VER")

RESULT_DEVEL=$(getRPM liblsapi-devel-"$VER")

if [ -n "$RESULT" -a -n "$RESULT_DEVEL" ];then
rpm -Uhv "$RESULT" "$RESULT_DEVEL" --oldpackage
else
yum install -y liblsapi liblsapi-devel --disableexcludes=all "$REPOSIT"
fi

else

yum install -y liblsapi liblsapi-devel --enablerepo=cloudlinux-updates-testing --disableexcludes=all

fi

IS_CL7=$(uname -r | grep '\.el7')
if [ -n "$IS_CL7" ];then
  yum install -y criu-lve criu-lve-devel crit-lve --enablerepo=cloudlinux-updates-testing --disableexcludes=all
fi

if [ ! -e /etc/cl.selector/lsphp -a -e /usr/sbin/cagefsctl -a -e /etc/cl.selector ]; then
    ln -s /usr/local/bin/lsphp /etc/cl.selector/lsphp
    /usr/sbin/cagefsctl --update-etc
    RES=`cat /etc/cl.selector/native.conf | grep lsphp=/usr/local/bin/lsphp `
    if [ -z "$RES" ]; then
        echo "lsphp=/usr/local/bin/lsphp" >> /etc/cl.selector/native.conf
    fi
    /usr/sbin/cagefsctl --setup-cl-selector

    echo "Reconfiguration completed"
fi

if [ ! -e "$SOCKPATH" ]; then
    mkdir -p "$SOCKPATH"   
fi

chown apache:apache "$SOCKPATH"
chmod 755 "$SOCKPATH"


