# PHP upgrade script
# description: PHP updater including mods and fpm-pools
#vars
read -p "Please enter the old php version (e.g. 7.2): " PHPOLD
read -p "Please enter the new php version that is to be installed: " PHPNEW
 
if grep -r sury /etc/apt/sources.list* > /dev/null 2> /dev/null;
then
    echo "Sury repo is allready installed!! No need to install"
    echo "apt-get update"
        apt-get update
else
        #install sury repo
        apt-get -y install apt-transport-https lsb-release ca-certificates curl
        wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
        sh -c 'echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list'
        apt-get update
fi
 
 
if dpkg -l php${PHPNEW}-fpm > /dev/null 2> /dev/null;
then
    echo "php$PHPNEW is allready installed, skipping"
else
        echo "Install $PHPNEW from sury packages..."
        # Dump the modules
        /usr/bin/php${PHPOLD} -m > /root/php${PHPOLD}modules
        # remove invalid modules
        sed -i -e '/\[PHP\ Modules\]/d' /root/php${PHPOLD}modules
        # remove zend opcache (does not exist in install)
        sed -i -e '/Zend/d' /root/php${PHPOLD}modules
        # remove empty lines
        sed -i -e '/^$/d' /root/php${PHPOLD}modules
        # cp old php to install
        cp /root/php${PHPOLD}modules /root/php${PHPNEW}modules
        # insert php-fpm
        echo "fpm" >> /root/php${PHPNEW}modules
        # set modules ready to install
        sed -i -e "s/^/apt-get install php${PHPNEW}-/" /root/php${PHPNEW}modules
        # set -y flag
        sed -i -e 's/$/ -y/' php${PHPNEW}modules
        # make executable
        chmod +x php${PHPNEW}modules
        # Install phpnew from sury
        echo -n "Do you want to install php${PHPNEW} from sury? (Yy/n)?"
            read answer
            if [ "$answer" != "${answer#[Yy]}" ] ;then
            echo "#### INSTALLING PHP${PHPNEW} from SURY ####"
            /bin/bash /root/php${PHPNEW}modules
            else
                echo "No, skipping install"
            fi
        # cp php ini file
        if [ -f "/etc/php/${PHPOLD}/fpm/php.ini" ]; then
            echo "php.ini old exist, copying"
            cp -v /etc/php/${PHPOLD}/fpm/php.ini /etc/php/${PHPNEW}/fpm/php.ini
        else
            echo "php.ini does not exist"
        fi
        # cp pool files
        if [ -d "/etc/php/${PHPOLD}/fpm/pool.d/" ]; then
            echo "pool.d old exist, copying"
            cp -rv /etc/php/${PHPOLD}/fpm/pool.d/ /etc/php/${PHPNEW}/fpm/
        else
            echo "FPM pool does not exist"
        fi
        # change sockets to new php version
        sed -i -e "s/${PHPOLD}/${PHPNEW}/" /etc/php/${PHPNEW}/fpm/pool.d/*
    echo "reload fpm pools"
        /etc/init.d/php${PHPNEW}-fpm reload
echo "###"
echo "### IF EVERYTHING IS OK THEN YOU STILL NEED TO ENABLE php$PHPNEW IN APACHE2 OR NGINX ###"
echo "###"
fi
