#!/bin/bash

if [[ -e /etc/system-release ]]; then
    DISTRO=`cat /etc/system-release`
else
    DISTRO=`cat /etc/issue`
fi

is_ubuntu() {
  [[ $DISTRO =~ ^Ubuntu ]]
}

function is_centos7 {
  if [[ $DISTRO == "CentOS Linux release 7"* ]]; then
      true
  else
      false
  fi
}

SSL_FOLDER="/etc/letsencrypt"

if is_centos7; then
    echo "Host OS is Centos7"
    BINARY_TARGET="centos7"
    APACHE_SERVICE_NAME="httpd"
    APACHE_CONF_BASE="/etc/$APACHE_SERVICE_NAME/conf.d"
    SUPERVISOR_SERVICE_NAME="supervisord"
    NGINX_USER="nginx"
    PHP_FPM="/var/run/php-fpm.sock"
    AWSTATS_CGI_PATH="/usr/share/awstats/wwwroot/cgi-bin/awstats.pl"
    AWSTATS_ICON_PATH="/usr/share/awstats/wwwroot/icon/"
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://streaming.center/dist/centos/yum.repos.d/CentOS-Base.repo
    wget  --no-check-certificate -O /tmp/iptables_geoip.tar.gz https://streaming.center/dist/iptables_geoip.tar.gz
elif is_ubuntu; then
    echo "Host OS is Ubuntu"
    UBUNTU_RELEASE=`lsb_release -a | grep ^Release | awk '{print $2}'`
    if [[ "$UBUNTU_RELEASE" = "20.04" ]]; then
        BINARY_TARGET="ubuntu20"
        PHP_VERSION="7.4"
        PIP_OPTIONS=""
        AVCODEC_PACKAGES="libavcodec58 libavformat58"
        python3 -m pip install --upgrade pip
        python3 -m pip install --upgrade setuptools wheel twine check-wheel-contents
        pip3 install certbot==3.0.1
        pip3 install certbot-apache==3.0.1
        pip3 install certbot-nginx==3.0.1
        rm -f /usr/bin/certbot
        ln -s /usr/local/bin/certbot /usr/bin/certbot
    elif [[ "$UBUNTU_RELEASE" = "22.04" ]]; then
        BINARY_TARGET="ubuntu22"
        PHP_VERSION="8.1"
        PIP_OPTIONS=""
        AVCODEC_PACKAGES="libavcodec58 libavformat58"

    elif [[ "$UBUNTU_RELEASE" = "24.04" ]]; then
        BINARY_TARGET="ubuntu24"
        PHP_VERSION="8.3"
        PIP_OPTIONS="--break-system-packages"
        AVCODEC_PACKAGES="libavcodec60 libavformat60"
    elif [[ "$UBUNTU_RELEASE" = "26.04" ]]; then
        BINARY_TARGET="ubuntu26"
        PHP_VERSION="8.4"
        PIP_OPTIONS="--break-system-packages"
        AVCODEC_PACKAGES="libavcodec62 libavformat62"
    fi

    APACHE_SERVICE_NAME="apache2"
    APACHE_CONF_BASE="/etc/$APACHE_SERVICE_NAME/sites-enabled"
    SUPERVISOR_SERVICE_NAME="supervisor"
    NGINX_USER="www-data"
    PHP_FPM="/var/run/php/php-fpm.sock"
    AWSTATS_CGI_PATH="/usr/lib/cgi-bin/awstats.pl"
    AWSTATS_ICON_PATH="/usr/share/awstats/icon/"
    if [[ "$UBUNTU_RELEASE" != "20.04" && "$UBUNTU_RELEASE" != "22.04" && "$UBUNTU_RELEASE" != "24.04" && "$UBUNTU_RELEASE" != "26.04" ]]; then
        echo "This version of Ubuntu is not currently supported. Supported versions: 20.04, 22.04, 24.04, 26.04 (LTS)"
        exit
    fi

else
    echo "Unsupported Distro: $DISTRO" 1>&2
    exit 1
fi

if [ -f /opt/bin/utils.ini ]; then
    echo "Previous installation found"
else
    echo "Previous installation NOT found"
    exit
fi

[ ! -d "/opt/sc_radio" ] && echo "Update is not possible" && exit

MAIN_VHOST=`cat /opt/bin/utils.ini | grep MAIN_VHOST | awk '{print $3}'`
SC_PANEL_PORT=`cat /opt/bin/utils.ini | grep SC_ADMIN_PORT | awk '{print $3}'`
USER_BASEDIR=`cat /opt/bin/utils.ini | grep USER_BASEDIR | awk '{print $3}'`
MYSQL_PASS=`cat /opt/bin/utils.ini | grep SU_PASSWD | awk '{print $3}'`
NGINX_CONF_BASE="/etc/nginx/conf.d"

SSL_DONE=0
PYTHON3_LIBPATH=`python3 -c "import sys; print(min(list(x for x in sys.path if x), key=len))"`
MY_PWD=`pwd`
SRC_DIR=$MY_PWD
PYTHON3_VERSION=`python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))'`
echo "Python3 version: $PYTHON3_VERSION"
if [ -z "$PYTHON3_VERSION" ]; then
    echo "Python3 version is undefined, abort"
    exit
fi

if is_centos7; then
    packages=(php-fpm psmisc sox libmad lame-libs python3-devel davfs2 libebur128)
    echo "Installing additional packages"
    for p in ${packages[*]}
    do
        if rpm -q $p > /dev/null; then
	    echo "Package '$p' already installed, skip"
        else
	    echo "Installing package $p..."
	    # yum -y install $p
	    [ $? -eq 0 ] && echo "Package $p has been installed successfully"
	    [ $? -ne 0 ] && echo "Package $p installation failed!" && exit
        fi
    done
    if rpm -q sox-plugins-freeworld > /dev/null; then
        echo "Package 'sox-plugins-freeworld' already installed, skip"
    else
        echo "Installing package sox-plugins-freeworld..."
        rpm -i http://li.nux.ro/download/nux/dextop/el7/x86_64/sox-plugins-freeworld-14.4.1-3.el7.nux.x86_64.rpm
        [ $? -eq 0 ] && echo "Package sox-plugins-freeworld has been installed successfully"
        [ $? -ne 0 ] && echo "Package sox-plugins-freeworld installation failed!" && exit
    fi

    if rpm -q audiowaveform > /dev/null; then
        echo "Package 'audiowaveform' already installed, skip"
    else
        echo "Installing package audiowaveform..."
        yum install -y https://github.com/bbc/audiowaveform/releases/download/1.5.1/audiowaveform-1.5.1-1.el7.x86_64.rpm
        [ $? -eq 0 ] && echo "Package audiowaveform has been installed successfully"
        [ $? -ne 0 ] && echo "Package audiowaveform installation failed!" && exit
    fi
    echo "Finished installing additional packages"

    sed -i 's/listen \= 127.0.0.1:9000/listen \= \/var\/run\/php-fpm.sock/' /etc/php-fpm.d/www.conf

    MYSQL_CONFIG=/etc/my.cnf
    if [ ! -f /etc/systemd/system/mariadb.service.d/limits.conf ]; then
        echo "Raising MySQL limit on the maximum number of open connections to 2000"
        mkdir /etc/systemd/system/mariadb.service.d/
        printf "[Service]\nLimitNOFILE=infinity\n" > /etc/systemd/system/mariadb.service.d/limits.conf
        systemctl daemon-reload
    fi
    if ! grep -qF "max_connections" $MYSQL_CONFIG
    then
        sed '/\[mysqld\]/a max_connections = 2000\' -i $MYSQL_CONFIG
        service mariadb restart
    fi
    wget --no-check-certificate -O /tmp/iptables_geoip_centos.tar.gz https://streaming.center/dist/iptables_geoip_centos.tar.gz
elif is_ubuntu; then
    apt update
    DEBIAN_FRONTEND=noninteractive apt install -y davfs2 iptables libebur128-1 $AVCODEC_PACKAGES uwsgi-plugin-python3 nscd libffi-dev libgeoip2-perl libmaxminddb0
    # TODO: Check if it is still required
    sed -i 's/listen \= 127.0.0.1:9000/listen \= \/var\/run\/php-fpm.sock/' /etc/php/$PHP_VERSION/fpm/pool.d/www.conf
    rm -f /etc/apache2/sites-enabled/000-default.conf

    # Enable MySQL root connections for non-root users
    mysql -u root -p$MYSQL_PASS -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASS';" mysql;
    mysql -u root -p$MYSQL_PASS -e "flush privileges;"
    wget  --no-check-certificate -O /tmp/iptables_geoip.tar.gz https://streaming.center/dist/iptables_geoip.tar.gz
fi

### VENV via UV
# UV_DIR="/opt/sc_uv"
# VENV_DIR="/opt/sc_venv"
# UV_BIN="$UV_DIR/uv"
# UV_PYTHON_INSTALL_DIR="/opt/sc_python"

# if [ ! -d "$VENV_DIR" ]; then
#     echo "Creating directory for uv at $UV_DIR..."
#     mkdir -p "$UV_DIR"
#     echo "Installing uv into $UV_DIR..."
#     curl -Ls https://astral.sh/uv/install.sh | env UV_INSTALL_DIR="$UV_DIR" bash
#     if [ ! -f "$UV_BIN" ]; then
#         echo "uv installation failed."
#         exit 1
#     fi
#     echo "uv installed successfully at $UV_BIN"
#     echo "Creating virtual environment with Python 3.12 at $VENV_DIR..."
#     source "$UV_DIR/env"
#     UV_PYTHON_INSTALL_DIR="$UV_PYTHON_INSTALL_DIR" "$UV_BIN" venv --python 3.12 "$VENV_DIR"
#     if [ ! -d "$VENV_DIR" ]; then
#         echo "Virtual environment creation failed."
#         exit 1
#     fi
#     # Install pip requirements
#     echo "Installing pip requirements in the virtual environment..."
#     source "$VENV_DIR/bin/activate"
#     "$UV_BIN" pip install -r /opt/sc_radio/requirements3.12.txt
#     "$UV_BIN" pip install -r /opt/web_panel/backend/requirements3.12.txt
#     source "$VENV_DIR/bin/deactivate"
# fi
# echo "Virtual environment successfully created with Python 3.12 at $VENV_DIR"


# Binaries

# LoudGain
echo "Installing Loud Gain..."
rm -f /usr/local/bin/loudgain
wget --no-check-certificate -O /usr/local/bin/loudgain https://streaming.center/dist/binaries/$BINARY_TARGET/loudgain
chmod +x /usr/local/bin/loudgain

if is_centos7; then
    rm -f /tmp/libmvec.tar.gz
    if [ -f /usr/lib64/libmvec.so.1 ]; then
        echo "Libmvec alredy installed"
    else
        if wget -O /tmp/libmvec.tar.gz https://streaming.center/dist/lib/libmvec.tar.gz; then
        tar -xzf /tmp/libmvec.tar.gz -C /tmp
        cp /tmp/libmvec/* /usr/lib64/
        echo "libmvec installed"
        fi
    fi
fi

echo "Installing Stereo Tool..."
#if wget -O /tmp/stereo_tool_cmd_64 https://www.stereotool.com/download/stereo_tool_cmd_64; then
if wget -O /tmp/stereo_tool_cmd_64 https://streaming.center/dist/binaries/stereo_tool_cmd_64; then
    mkdir -p /opt/stereo_tool/
    mv /tmp/stereo_tool_cmd_64 /opt/stereo_tool/stereo_tool_cmd_64
    chmod +x /opt/stereo_tool/stereo_tool_cmd_64
fi

# SC binaries
echo "Updating radio service binaries..."
rm -f /usr/local/bin/radiopoint
rm -f /usr/local/bin/content_indexer
wget -O /usr/local/bin/radiopoint https://streaming.center/dist/binaries/$BINARY_TARGET/radiopoint
wget -O /usr/local/bin/content_indexer https://streaming.center/dist/binaries/$BINARY_TARGET/content_indexer
chmod +x /usr/local/bin/radiopoint
chmod +x /usr/local/bin/content_indexer
chmod +x /opt/shoutcast1/bin/sc_serv
chmod +x /opt/shoutcast2/bin/sc_serv
chmod +x /opt/shoutcast2/bin/sc_serv2.6


# Icecast-kh binary file
#if [ -f /opt/icecast/bin/icecast-kh ]; then
#    echo "Icecast-kh is already installed"
#else
#rm -f /opt/icecast/bin/icecast-kh
echo "Downloading Icecast..."
rm -f /opt/icecast/bin/icecast
wget --no-check-certificate -O /opt/icecast/bin/icecast https://streaming.center/dist/binaries/icecast/$BINARY_TARGET/icecast
chmod +x /opt/icecast/bin/icecast


echo "Downloading Icecast-kh..."
rm -f /opt/icecast/bin/icecast-kh
wget -O /opt/icecast/bin/icecast-kh https://streaming.center/dist/binaries/icecast/$BINARY_TARGET/icecast-kh
chmod +x /opt/icecast/bin/icecast-kh
#fi

# SC2.6 binary file
echo "Downloading Shoutcast2.6..."
rm -f /opt/shoutcast2/bin/sc_serv2.6
wget -O /opt/shoutcast2/bin/sc_serv2.6 https://streaming.center/dist/binaries/shoutcast2/bin/sc_serv2.6
chmod +x /opt/shoutcast2/bin/sc_serv2.6

# Copy icecast www files
echo "Installing Icecast web files"
wget -O /tmp/icecast-files.tar.gz https://streaming.center/dist/icecast-files.tar.gz
tar -xzf /tmp/icecast-files.tar.gz --directory /opt/icecast
rm -f /tmp/icecast-files.tar.gz

# Radio web control panel
echo "Installing Web interface"
wget -O /tmp/web_panel.tar.gz https://streaming.center/dist/web_panel$PYTHON3_VERSION.tar.gz
rm -rf /opt/web_panel
mkdir /opt/web_panel
tar -xzf /tmp/web_panel.tar.gz --directory /opt/web_panel
rm -f /tmp/web_panel.tar.gz

# New FE
rm -rf mkdir /opt/web_panel_fe
mkdir /opt/web_panel_fe
rm -rf /tmp/web_panel_fe.tar.gz
wget -O /tmp/web_panel_fe.tar.gz https://streaming.center/dist/web_panel_fe.tar.gz
rm -rf /opt/web_panel/release/*
mkdir -p /opt/web_panel/release/
tar -xzf /tmp/web_panel_fe.tar.gz --directory /opt/web_panel/release/
rm -f /tmp/web_panel_fe.tar.gz

pip3 install $PIP_OPTIONS --upgrade -r /opt/web_panel/backend/requirements$PYTHON3_VERSION.txt

# Updating modules
echo "Updating accounting modules"
'cp' -rf "/opt/web_panel/backend/billing/python3/radiotochka/" "$PYTHON3_LIBPATH/"

echo "Intalling hosting Web interface..."
wget -O /tmp/sc_radio.tar.gz https://streaming.center/dist/sc_radio$PYTHON3_VERSION.tar.gz
tar -xzf /tmp/sc_radio.tar.gz --directory /opt/sc_radio
rm -f /tmp/sc_radio.tar.gz
pip3 install $PIP_OPTIONS --upgrade -r /opt/sc_radio/requirements$PYTHON3_VERSION.txt

chown sc_radio:sc_radios -R /opt/sc_radio

sed -i 's:https\://everestcast.com/order/:https\://my.everestcast.com/:g' /opt/bin/utils.ini

python3 /opt/sc_radio/manage.py migrate > /dev/null 2>&1

if [[ $MAIN_VHOST =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    USING_VHOST=0
else
    USING_VHOST=1
fi

if is_centos7; then
    'cp' -f /usr/bin/uwsgi3 /usr/bin/uwsgi
    chmod +x /usr/bin/uwsgi3
    chmod +x /usr/bin/uwsgi
fi

if [ -f /etc/letsencrypt/live/$MAIN_VHOST/cert.pem ]; then
    SSL_DONE=1
fi

# Download utils
wget -O /tmp/setup-utils.tar.gz https://streaming.center/dist/setup-utils$PYTHON3_VERSION.tar.gz
tar -xzf /tmp/setup-utils.tar.gz --directory $MY_PWD
rm -f /tmp/setup-utils.tar.gz

# Apache default config
if [ -f $APACHE_CONF_BASE/sc_radio.conf ]; then
    echo "Default Apache configuration already installed"
else
    cp $SRC_DIR/utils/etc/httpd/sc_radio.conf $APACHE_CONF_BASE/sc_radio.conf
    sed -i "s:MAIN_VHOST:$MAIN_VHOST:g" $APACHE_CONF_BASE/sc_radio.conf
    service httpd restart
    service apache2 restart
fi

'cp' -f $SRC_DIR/utils/etc/nginx/nginx.conf $NGINX_CONF_BASE/../nginx.conf
sed -i "s/user nginx/user $NGINX_USER/" $NGINX_CONF_BASE/../nginx.conf

cp -f $SRC_DIR/utils/update_icecast_ssl.py /opt/bin/
cp -f /opt/bin/update_icecast_ssl.py $SSL_FOLDER/renewal-hooks/deploy/

# Fix icecast.pem cert order (fullchain first, then privkey) for any existing files
for domain_dir in "$SSL_FOLDER/live"/*/; do
    icecast_pem="$domain_dir/icecast.pem"
    fullchain="$domain_dir/fullchain.pem"
    privkey="$domain_dir/privkey.pem"
    if [ -f "$icecast_pem" ] && [ -f "$fullchain" ] && [ -f "$privkey" ]; then
        echo "Fixing icecast.pem cert order for $domain_dir..."
        cat "$fullchain" "$privkey" > "$icecast_pem"
    fi
done

if [ $USING_VHOST == 1 ] && [ $SSL_DONE == 0 ]; then
    read -r -p "Do you want to create Let's Encrypt SSL certificate for your domain? [y/N] " ssl
    if [[ "$ssl" =~ ^([yY][eE][sS]|[yY])+$ ]]
    # Ssl accepted
    then
        /opt/bin/ssl_enable
        SSL_DONE=1
    else
       echo "SSL setup skipped"
    fi

else
    USING_VHOST=0
fi

if [ $SSL_DONE == 1 ]; then
    sed -i "s|http://localhost:8000|https://$MAIN_VHOST:$SC_PANEL_PORT|" /opt/sc_radio/static/_nuxt/*.js
else
    sed -i "s/localhost:8000/$MAIN_VHOST:$SC_PANEL_PORT/" /opt/sc_radio/static/_nuxt/*.js
fi

# Utils

#cp -f $MY_PWD/utils/sc_accounts.py /opt/bin/
#cp -f $MY_PWD/utils/awstats.py /opt/bin/
#cp -f $MY_PWD/utils/sc_stats.py /opt/bin/
#cp -f $MY_PWD/utils/sc_utils.py /opt/bin/

cp -f $MY_PWD/utils/sc_accounts /opt/bin/
cp -f $MY_PWD/utils/sc_backup /opt/bin/
cp -f $MY_PWD/utils/awstats /opt/bin/
cp -f $MY_PWD/utils/sc_stats /opt/bin/
cp -f $MY_PWD/utils/cgi-bin.php /etc/nginx/
cp -f $MY_PWD/utils/sc_utils.pyc /opt/bin/
cp -f $MY_PWD/utils/sc_doctor.py /opt/bin/
cp -f $MY_PWD/utils/sc_speedtest.py /opt/bin/

cp -f $MY_PWD/utils/change_host /opt/bin/
cp -f $MY_PWD/utils/ssl_enable /opt/bin/

cp -f $MY_PWD/utils/change_account_passwords /opt/bin/
cp -f $MY_PWD/utils/change_ftp_passwords /opt/bin/


chmod +x /opt/bin/sc_accounts
chmod +x /opt/bin/sc_backup
chmod +x /opt/bin/awstats
chmod +x /opt/bin/sc_stats
chmod +x /opt/bin/sc_speedtest.py


service $SUPERVISOR_SERVICE_NAME restart
supervisorctl restart sc_radio
service php-fpm restart
service php$PHP_VERSION-fpm restart
systemctl enable php-fpm
systemctl enable php$PHP_VERSION-fpm
systemctl enable proftpd
killall -SIGHUP icecast
killall -SIGHUP icecast-kh

echo "Setting up Geo Blocking"
source $SRC_DIR/utils/install_iptables_geoip

rm -rf $MY_PWD/utils/

# MySQL timezone support
#if is_centos7; then
#    # yum update -y tzdata
#elif is_ubuntu; then
apt --only-upgrade -y install tzdata
apt-get -y install -m tzdata-legacy
#fi
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p$MYSQL_PASS mysql

# FTP udates
if is_centos7; then
    service mariadb force-reload
    # FTP encryption
    sed -i '/LoadModule mod_sql_passwd.c/s/^#//g' /etc/proftpd.conf
    sed -i 's/SQLAuthTypes Plaintext/SQLPasswordEngine on\nSQLAuthTypes SHA512 Plaintext/g' /etc/proftpd.conf
    mysql -u root -p$MYSQL_PASS -e 'ALTER TABLE `users` CHANGE `password` `password` VARCHAR(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT "";' proftpd
    service proftpd restart
    # Security fix
    mysql -u root -p$MYSQL_PASS -e 'UPDATE `radiousers` SET `is_active`=0 WHERE account_type=2;' sc_billing;
    
elif is_ubuntu; then
    service mysql reload
    if grep -q "^DefaultRoot" /etc/proftpd/proftpd.conf
    then
        echo "User chroot already enabled in Proftpd"
    else
        echo "Patching ProFtpd to support user chroot"
        echo "DefaultRoot ~ !adm" >> /etc/proftpd/proftpd.conf
        service proftpd restart
    fi

    # Make journald system log smaller
    sed -i '/^#SystemMaxUse/s/^#//' /etc/systemd/journald.conf
    sed -i 's/SystemMaxUse.*/SystemMaxUse=50M/' /etc/systemd/journald.conf
    systemctl restart systemd-journald
    rm -f /etc/cron.d/awstats

    chmod +x /usr/bin/uwsgi_python3
    if [ ! -f /usr/bin/uwsgi_python3 ]; then
        ln -s `ls /usr/bin/uwsgi_python3* | sort | tail -n1` /usr/bin/uwsgi_python3
    fi

fi


# AWSTATS default language
for filename in /etc/awstats/awstats.*.conf; do
    sed -i 's/Lang="ru"/Lang="auto"/' $filename
    sed -i "s/&quot;%host %other %time2 %method %url %code %ua %bytesd %other %other&quot;/%host %other %time2 %method %url %code %ua %bytesd %other %other/" $filename
done

# GEOIP
GEOIP_FILE="/usr/share/GeoIP/GeoLite2-City.mmdb"
if [ -f "$GEOIP_FILE" ] && [ -z "$(find "$GEOIP_FILE" -mtime +30)" ]; then
    echo "GeoIP files alredy installed and up to date"
else
    echo "Downloading GeoIP files..."
    wget -O /tmp/GeoIP.tar.gz https://streaming.center/dist/GeoIP.tar.gz
    tar -C /usr/share -xzf /tmp/GeoIP.tar.gz
    rm -f /tmp/GeoIP.tar.gz
fi

# Download FFMPEG
if [[ "$UBUNTU_RELEASE" != "22.04" ]]; then
    rm -f /usr/bin/ffmpeg
    echo "Downloading FFMPEG..."
    wget -O /usr/bin/ffmpeg https://streaming.center/dist/binaries/ffmpeg
    chmod +x /usr/bin/ffmpeg
fi

#fi

# Add backup script
CRON_RULE=`cat /etc/crontab | grep "/opt/bin/sc_backup"`
if [ -z "$CRON_RULE" ]; then
    echo "*/15 * * * * root python3 /opt/bin/sc_backup 1>/dev/null 2>/dev/null" >> /etc/crontab
fi

for filename in /etc/awstats/awstats*.conf; do
    sed -i "s/http:\/\/www.radio-tochka.com\///" $filename
    sed -i "s/logo.jpg/awstats_logo6.png/" $filename
done

echo "Updating radio accounts..."
for dir in $USER_BASEDIR*/
do
    dir=${dir%*/}

    userdir=${dir##*/}
    if [ -d "$USER_BASEDIR$userdir/app" ] && [ -d "$USER_BASEDIR$userdir/conf" ]  && [ -d "$USER_BASEDIR$userdir/home" ] && [ -f "$NGINX_CONF_BASE/$userdir.conf" ]; then
        echo "Updating $userdir"

        sed s/utf8\'/utf8mb4\'/g -i $USER_BASEDIR$userdir/app/settings_local.py

        # 'cp' -f /opt/icecast/admin/xspf.xsl $USER_BASEDIR$userdir/icecast/admin/
        'cp' -rf /opt/icecast/ $USER_BASEDIR$userdir
        BACKEND_URL=`cat $USER_BASEDIR$userdir/app/media/index.html | grep BACKEND_BASE_URL | awk '{print $4}'`
        'cp' -rf /opt/web_panel/backend/. $USER_BASEDIR$userdir/app
        'cp' -rf /opt/web_panel/release/. $USER_BASEDIR$userdir/app/media
        sed -i -E "s~var BACKEND_BASE_URL = (.*?)~var BACKEND_BASE_URL = $BACKEND_URL~g" $USER_BASEDIR$userdir/app/media/index.html
        $USER_BASEDIR$userdir/app/manage.py migrate > /dev/null 2>&1
        $USER_BASEDIR$userdir/app/manage.py regenerate_channels_config > /dev/null 2>&1
        $USER_BASEDIR$userdir/app/manage.py recreate_supervisor_config > /dev/null 2>&1
        $USER_BASEDIR$userdir/app/manage.py recreate_shoutcast_config > /dev/null 2>&1
        $USER_BASEDIR$userdir/app/manage.py recreate_nginx_config > /dev/null 2>&1
        $USER_BASEDIR$userdir/app/manage.py recreate_awstats_config > /dev/null 2>&1
        chown $userdir:$userdir -R $USER_BASEDIR$userdir/
        chown $userdir:sc_radios -R $USER_BASEDIR$userdir/log/radiopoint
        chmod 666 $USER_BASEDIR$userdir/log/radiopoint/log.log 2>/dev/null
        chmod 666 $USER_BASEDIR$userdir/log/django/django.log 2>/dev/null
        supervisorctl reread
        supervisorctl update $userdir
        supervisorctl restart $userdir

    fi
done
cd /etc/nginx/conf.d
sed -i "s/ssl on;//" *

#if [ $SSL_DONE == 1 ]; then
#    sed -i -E s"/listen\s+([[:digit:]]+);/listen \1 ssl;/" *
#fi
service nginx restart

if [ -f "/opt/bin/sc_post_update_hook" ]; then
    echo "Post-update hook found in /opt/bin/sc_post_update_hook, running..."
    /opt/bin/sc_post_update_hook
fi


# Update version number
VERSION=`curl -s 'https://streaming.center/dist/changelog.json' | python3 -c "import sys,json; print(list(json.load(sys.stdin).keys())[0])"`
if [ -z "$VERSION" ]
then
      echo "Failed to load version number"
else
    echo "Streaming.center Version $VERSION installation is complete"
    mysql -u root -p$MYSQL_PASS -e "UPDATE license SET version='$VERSION';" sc_billing;
fi
