#!/bin/bash

#
# Name:		gen-apps-list.sh
# Version:      1.19
#
# (c) 2016-2022, Rapidseedbox, alexey@rapidseedbox.com
#

SCRIPT_VER="$( grep -m 1 -E '^#\s*Version:\s+' "${0}" | awk '{print $NF}' )"
APP_DB_VER="${SCRIPT_VER}"
SC_DIR="$( dirname "${0}" )"
INSTALLERS_DB="${SC_DIR}/support/installers.db"
INSTALLERS_DB_WHMCS="${SC_DIR}/support/installers-whmcs.db"

echo "SC_DIR: [${SC_DIR}]"

# git clone git@github.com:RapidSeedbox/Proxy-Puppeteer-API.git
cd "${SC_DIR}/support/Proxy-Puppeteer-API" || exit 1
git pull
tar zcf ../Proxy-Puppeteer.tar.gz --exclude=".git*" .
cd - > /dev/null || exit 1

# Rebuild `rsb-dashboard` package
cd "${SC_DIR}/support/rsb-dashboard" || exit 1
grep -E "\\\$version\s+=\s+" "./dashboard/inc/config.php" | awk "{print \$NF}" | tr -d "\";v" > version.id
#convert "./dashboard/img/logo-dark-TEMPLATE.svg" \
#        -background none \
#        -gravity southeast \
#        -pointsize 16 \
#        -fill black \
#        -annotate +5+2 "v $( cat "version.id" )" \
#      "./dashboard/img/logo-dark.png"
#convert "./dashboard/img/logo-light-TEMPLATE.svg" \
#        -background none \
#        -gravity southeast \
#        -pointsize 16 \
#        -fill black \
#        -annotate +5+2 "v $( cat "version.id" )" \
#      "./dashboard/img/logo-light.png"
tar zcf ../rsb-dashboard.tar.gz --exclude=".git*" --exclude="*~" .
cd - > /dev/null || exit 1

rm -fv "${SC_DIR}/categorized-apps.list.auto"
rm -fv "${INSTALLERS_DB}"
rm -fv "${INSTALLERS_DB_WHMCS}"

sqlite3 "${INSTALLERS_DB}" <<-EOF
	CREATE TABLE version ( 
            id TEXT,
            os_release TEXT
          );
	INSERT INTO version ( id ) VALUES ( '${APP_DB_VER}' );
	CREATE TABLE category    (
	    id   INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
	    name TEXT
	  );
	CREATE TABLE application (
	    id                INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
	    cat_id            INTEGER,
	    name              TEXT,
	    unique_id         TEXT,
	    about             TEXT,
	    version           TEXT,
	    check_ver_cmd     TEXT,
	    pkgname           TEXT,
	    pkgversion        TEXT,
	    sys_pkg_name      TEXT,
	    maintainer        TEXT,
	    homepage          TEXT,
	    supported_on      TEXT,
	    depends           TEXT,
	    conflicts         TEXT,
	    breaks            TEXT,
	    scope             TEXT,
	    extra_vars        TEXT,
	    description       TEXT,
	    status            TEXT,
	    date              INTEGER,
	    password          TEXT,
	    is_upgradable     TEXT,
	    upgrade_ver_cmd   TEXT,
	    upgrade_ver       TEXT
	  );
	EOF

sqlite3 "${INSTALLERS_DB_WHMCS}" <<-EOF
	CREATE TABLE version ( 
            id TEXT,
            os_release TEXT
          );
	INSERT INTO version ( id ) VALUES ( '${APP_DB_VER}' );
	CREATE TABLE category    (
	    id   INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
	    name TEXT
	  );
	CREATE TABLE application (
	    id                INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
	    cat_id            INTEGER,
	    name              TEXT,
	    version           TEXT,
	    pkgname           TEXT,
	    scope             TEXT,
	    status            TEXT,
	    date              INTEGER,
	    password          TEXT,
	    is_upgradable     TEXT,
	    upgrade_ver       TEXT
	  );
	EOF

find "${SC_DIR}" -mindepth 1 -maxdepth 1 -name "install_*.sh" -print | sort |
    while read -r s ; do
        grep -e '^APP_CATEGORY=".*"' "${s}" > /dev/null 2>&1 || continue
        app_enabled=$( cat "${s}" | grep -e '^APP_ENABLED=".*"' | sed -e 's|^APP_ENABLED="\(.*\)"|\1|' )
        [ "${app_enabled}" = "yes" ] || continue
        name=""
        unique_id=""
        about=""
        version=""
        pkgversion=""
        pkgname=""
        maintainer=""
        homepage=""
        supported_on=""
        depends=""
#        conflicts=""
        breaks=""
        scope=""
        extra_vars=""
        description=""
        pkgname="${s##*/install_}"
        pkgname="${pkgname%.sh}"
        name="$( cat "${s}" | grep -e '^APP=".*"' | sed -e 's|^APP="\(.*\)"|\1|' )"
        unique_id="$( echo "${name}" | sha1sum | awk '{print $1}' )"
        version="$( cat "${s}" | grep -e '^APP_VER=".*"' | sed -e 's|^APP_VER="\(.*\)"|\1|' )"
        app_check_ver_cmd="$( cat "${s}" \
                               | grep -e '^#><#APP_CHECK_VER_CMD=".*"' \
                               | sed -e 's|^#><#APP_CHECK_VER_CMD="\(.*\)"|\1|' )"
#        [ -z "${version}" ] \
#            && version=$( cat "${s}" | grep -e '^SCRIPT_VER=".*"' | sed -e 's|^SCRIPT_VER="\(.*\)"|\1|' )
        conflicts="$( cat "${s}" | grep -m 1 -e '^CONFLICTS=".*"' | sed -e 's|^CONFLICTS="\(.*\)"|\1|' )"
        pkgversion="$( cat "${s}" | grep -e '^SCRIPT_VER=".*"' | sed -e 's|^SCRIPT_VER="\(.*\)"|\1|' )"
        sys_pkg_name="$( cat "${s}" | grep -e '^SYS_PKG_NAME=".*"' | sed -e 's|^SYS_PKG_NAME="\(.*\)"|\1|' )"
        supported_on="$( cat "${s}" | grep -e '^SUPPORTED_ON=".*"' | sed -e 's|^SUPPORTED_ON="\(.*\)"|\1|' )"
        depends="$( cat "${s}" | grep -e '^DEPENDS=".*"' | sed -e 's|^DEPENDS="\(.*\)"|\1|' )"
        scope="$( cat "${s}" | grep -e '^APP_SCOPE=".*"' | sed -e 's|^APP_SCOPE="\(.*\)"|\1|' )"
        about_file="${SC_DIR}/about/${pkgname}.about"
        if [ -e "${about_file}" ] ; then
            about="$( cat "${about_file}" | iconv -f utf-8 -t ascii//translit | sed -e "s|'|''|g" )"
        fi
        if [ -e "${SC_DIR}/upgrade_${pkgname}.sh" ] ; then
            is_upgradable="yes"
            app_upgrade_ver_cmd="$( grep -m 1 -e '^#><#APP_UPGRADE_VER_CMD=".*"' \
                                     "${SC_DIR}/upgrade_${pkgname}.sh" \
                                         | sed -e 's|^#><#APP_UPGRADE_VER_CMD="\(.*\)"|\1|' )"
        else
            app_upgrade_ver_cmd=""
            is_upgradable="no"
        fi
        extra_vars=""
        for ss in \
         "RUTORRENT_DIRECTORY" \
         "APP_HOME" \
         "MEMORY_K_MIN" \
         "PLUGINS_DIRECTORY" \
         "APP_DIRECTORY" \
         "DAEMON_PORT" \
         "WEBUI_PORT" \
         "DELUGE_VER" \
         "RT_S_VER" \
         "SYS_PKG_NAME" \
         "STORED_PASSWORD_SERVICE" \
        ; do
            app_var="$( cat "${s}" | grep -m 1 -E "^${ss}=.*" )"
            if [ -n "${app_var}" ] ; then
                [ -n "${extra_vars}" ] && extra_vars="${extra_vars} ; "
                extra_vars="${extra_vars}${app_var}"
            fi
        done
        category="$( cat "${s}" | grep -m 1 -e '^APP_CATEGORY=".*"' | sed -e 's|^APP_CATEGORY="\(.*\)"|\1|' )"
        INF_FILE="${SC_DIR}/inf/${pkgname}.inf"
        if [ -e "${INF_FILE}" ] ; then
            AppName=$( perl -ne \
              'next if /^#/; $p=(s/^AppName:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${AppName}" ] && name="${AppName}"
            Category=$( perl -ne \
              'next if /^#/; $p=(s/^Category:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${Category}" ] && category="${Category}"
            Package=$( perl -ne \
              'next if /^#/; $p=(s/^Package:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${Package}" ] && pkgname="${Package}"
            AppVersion=$( perl -ne \
              'next if /^#/; $p=(s/^AppVersion:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${AppVersion}" ] && version="${AppVersion}"
            PackageVersion=$( perl -ne \
              'next if /^#/; $p=(s/^PackageVersion:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${PackageVersion}" ] && pkgversion="${PackageVersion}"
            Maintainer=$( perl -ne \
              'next if /^#/; $p=(s/^Maintainer:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${Maintainer}" ] && maintainer="${Maintainer}"
            Depends=$( perl -ne \
              'next if /^#/; $p=(s/^Depends:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${Depends}" ] && depends="${Depends}"
            Conflicts=$( perl -ne \
              'next if /^#/; $p=(s/^Conflicts:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${Conflicts}" ] && conflicts="${Conflicts}"
            Breaks=$( perl -ne \
              'next if /^#/; $p=(s/^Breaks:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${Breaks}" ] && breaks="${Breaks}"
            Replaces=$( perl -ne \
              'next if /^#/; $p=(s/^Replaces:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${Replaces}" ] && replaces="${Replaces}"
            Description=$( perl -ne \
              'next if /^#/; $p=(s/^Description:\s*/ / or (/^ / and $p)); s/,|\n|\([^)]+\)//mg; print if $p' \
                         < "${INF_FILE}" \
                         | sed -e 's/^[[:space:]]*\(.*\)/\1/g' | sed -e 's/^\(.*\)[[:space:]]*$/\1/g' )
            [ -n "${Description}" ] && description="${Description}"
        fi
        cat_id="$( sqlite3 "${INSTALLERS_DB}" "SELECT id FROM category WHERE name='${category}'" )"
        if [ -z "${cat_id}" ] ; then
            sqlite3 "${INSTALLERS_DB}" "INSERT INTO category ( name ) VALUES ( '${category}' );"
            cat_id="$( sqlite3 "${INSTALLERS_DB}" "SELECT id FROM category WHERE name='${category}'" )"
        fi
        cat_id_whmcs="$( sqlite3 "${INSTALLERS_DB_WHMCS}" "SELECT id FROM category WHERE name='${category}'" )"
        if [ -z "${cat_id_whmcs}" ] ; then
            sqlite3 "${INSTALLERS_DB_WHMCS}" "INSERT INTO category ( name ) VALUES ( '${category}' );"
            cat_id_whmcs="$( sqlite3 "${INSTALLERS_DB_WHMCS}" \
                                 "SELECT id FROM category WHERE name='${category}'" )"
        fi
        sqlite3 "${INSTALLERS_DB}" \
           "INSERT INTO application \
                           ( cat_id, name, unique_id, about, version, check_ver_cmd, \
                             pkgversion, sys_pkg_name, pkgname, \
                             maintainer, homepage, supported_on, scope, extra_vars, \
                             depends, conflicts, breaks, description, \
                             is_upgradable, upgrade_ver_cmd, upgrade_ver \
                           ) \
                    VALUES ( ${cat_id}, '${name}', '${unique_id}', '${about}', '${version}', \
                             '${app_check_ver_cmd}', \
                             '${pkgversion}', '${sys_pkg_name}', '${pkgname}', \
                             '${maintainer}', '${homepage}', '${supported_on}', '${scope}', '${extra_vars}', \
                             '${depends}', '${conflicts}', '${breaks}', '${description}', \
                             '${is_upgradable}', '${app_upgrade_ver_cmd}', '' \
                           );"
        sqlite3 "${INSTALLERS_DB_WHMCS}" \
           "INSERT INTO application \
                           ( cat_id, name, version, \
                             pkgname, \
                             scope, \
                             is_upgradable, upgrade_ver \
                           ) \
                    VALUES ( ${cat_id_whmcs}, '${name}', '${version}', \
                             '${pkgname}', \
                             '${scope}', \
                             '${is_upgradable}', '' \
                           );"
        echo "${category}/${name}/${pkgname}/${supported_on}/${is_upgradable}" \
             >> "${SC_DIR}/categorized-apps.list.auto"
    done

cp -fv "${SC_DIR}/categorized-apps.list.auto" "${SC_DIR}/support/"
