#!/bin/sh
[ "$SYNOPKG_PKGDEST" ] || SYNOPKG_PKGDEST="/volume1/@appstore/SynoBox"

# Package
PACKAGE="SynoBox"
DNAME="SynoBox"

SCRIPTS_DIR="$(dirname $0)"
PACKAGE_DIR=/var/packages/$PACKAGE

# Others
INSTALL_DIR="${SYNOPKG_PKGDEST}"
INSTALL_APP="${SYNOPKG_PKGDEST}/app"
RUNAS="synobox"
USER="synobox"
GROUP="users"

APACHE_PID=/var/run/httpd-sys.pid
APACHE_SERVICE=/usr/syno/etc/rc.d/S97apache-sys.sh
APACHE_SITES=/usr/syno/etc/sites-enabled
APACHE_CONF=${APACHE_SITES}/synobox.legacy.conf
LEGACY_CONF=${PACKAGE_DIR}/target/app/synobox.legacy.conf

# Version where last wizard is changed - upgrade impossible if old_version < this version
LAST_WIZARD_VER=399

check1 ()
{
    [ $1 -ne 0 ] && R=$((R+1))
    [ $1 -eq 0 ] && echo -n "$2... yes" || echo -n "$2... no"
    [ $1 -ne 0 ] && [ "$3" != "" ] && echo -n " (found $3)"
    echo ""
}

check2 ()
{
    [ $1 -ne 0 ] && W=$((W+1))
    [ $1 -eq 0 ] && echo -n "$2... yes" || echo -n "$2... no"
    [ $1 -ne 0 ] && [ "$3" != "" ] && echo -n " (found $3)"
    echo ""
}

check ()
{
    R=0
    W=0
    echo "-- check errors --"
    [ -d ${INSTALL_DIR} ] && find ${INSTALL_DIR} -user 1000 -exec chown root: {} \; &> /dev/null
    [ -d ${INSTALL_APP} ] &> /dev/null ; ok=$? ; check1 $ok "checking for app folder"
    [ -d ${INSTALL_APP}/var ] &> /dev/null ; ok=$? ; check1 $ok "checking for app/var folder"
    x=$( cd ${INSTALL_APP} ; ./busybox &> /dev/null ) ; ok=$? ; check1 $ok "checking for busybox"
    ( cd ${INSTALL_APP} ; id ${USER} || /usr/syno/sbin/synouser --add ${USER} "" "${DNAME} user" 0 "" 0 ) &> /dev/null
    ( cd ${INSTALL_APP} ; [ $(id -u ${USER}) -ge 1000 ] || (
        ./busybox deluser ${USER}
        /usr/syno/sbin/synouser --add ${USER} "" "${DNAME} user" 0 "" 0
    ) ) &> /dev/null
    x=$( cd ${INSTALL_APP} ; id -un 2>&1 ) ; [ "$x" == "root" ] ; ok=$? ; check1 $ok "checking for root current user" "$x"
    x=$( cd ${INSTALL_APP} ; id synobox &> /dev/null ) ; ok=$? ; check1 $ok "checking for ${USER} user"
    x=$( cd ${INSTALL_APP} ; grep "^administrators:" /etc/group &> /dev/null ) ; ok=$? ; check1 $ok "checking for administrators group"
    ( cd ${INSTALL_APP} ; [ -f /usr/syno/bin/synodsmnotify ] && cp -f /usr/syno/bin/synodsmnotify synodsmnotify && chown root:root synodsmnotify && chmod 4755 synodsmnotify ) &> /dev/null
    x=$( cd ${INSTALL_APP} ; [ -f /usr/syno/bin/synodsmnotify ] &> /dev/null ) ; ok=$? ; check1 $ok "checking for synodsmnotify"
    x=$( cd ${INSTALL_APP} ; ./busybox stat -c %a mypython 2>&1 ) ; [ "$x" == "755" ] ; ok=$? ; check1 $ok "checking for mypython 755 permissions" "$x"
    x=$( cd ${INSTALL_APP} ; ./mypython --version 2>&1 ) ; [ "$x" == "Python 3.3.2" ] ; ok=$?  ; check1 $ok "checking for mypython 3.3.2 version" "$x"
    x=$( cd ${INSTALL_APP} ; echo -e "import concurrent.futures" | ./mypython &> /dev/null ) ; ok=$? ; check1 $ok "checking for mypython module: concurrent.futures"
    x=$( cd ${INSTALL_APP} ; echo -e "import logging" | ./mypython &> /dev/null ) ; ok=$? ; check1 $ok "checking for mypython module: logging"
    x=$( cd ${INSTALL_APP} ; echo -e "import multiprocessing" | ./mypython &> /dev/null ) ; ok=$? ; check1 $? "checking for mypython module: multiprocessing"
    x=$( cd ${INSTALL_APP} ; echo -e "import sqlite3" | ./mypython &> /dev/null ; ok=$? ) ; check1 $ok "checking for mypython module: sqlite3"
    x=$( cd ${INSTALL_APP} ; echo -e "import ssl" | ./mypython &> /dev/null ) ; ok=$? ; check1 $ok "checking for mypython module: ssl"
    x=$( cd ${INSTALL_APP} ; echo -e "import sys\nprint(sys.getdefaultencoding())" | ./mypython 2>&1 ) ; [ "$x" == "utf-8" ] ; ok=$? ; check1 $ok "checking for utf-8 default encoding" "$x"
    x=$( cd ${INSTALL_APP} ; echo -e "import sys\nprint(sys.getfilesystemencoding())" | ./mypython 2>&1 ) ; [ "$x" == "ascii" ] ; ok=$? ; check1 $ok "checking for ascii file system encoding" "$x"
    x=$( su -s /bin/sh ${USER} -c "true" &> /dev/null ) ; ok=$? ; check1 $ok "checking for su ${USER}"
    ( cd ${INSTALL_APP} ; [ -f var/log/.htaccess ] && rm -f var/log/.htaccess ) &> /dev/null
    echo "errors found: $R"
    echo "-- check warnings --"
    [ -x ${APACHE_SERVICE} ] &> /dev/null ; ok=$? ; check2 $ok "checking for ${APACHE_SERVICE}"
    [ -f ${APACHE_PID} ] &> /dev/null ; ok=$? ; check2 $ok "checking for ${APACHE_PID}"
    [ -d ${APACHE_SITES} ] &> /dev/null ; ok=$? ; check2 $ok "checking for ${APACHE_SITES}"
    #[ -f ${APACHE_CONF} ] &> /dev/null ; ok=$? ; check2 $ok "checking for ${APACHE_CONF}"
    [ -f ${LEGACY_CONF} ] &> /dev/null ; ok=$? ; check2 $ok "checking for ${LEGACY_CONF}"
    x=$( cd ${INSTALL_APP} ; ./find synobox -printf '%T@' ) ; echo "testing ./find, result: $x"
    x=$( cd ${INSTALL_APP} ; ./mypython pyinotify_test.py &> /dev/null ) ; ok=$? ; check2 $ok "checking for pyinotify"
    echo "warnings found: $W"
    return $R
}

do_check ()
{
    check &> ${SCRIPTS_DIR}/install.log ; ok=$?
    [ $ok -eq 0 ] || (
        ( 
            echo "Installation failed !"
            echo "------------------------------------------"
            cat ${SCRIPTS_DIR}/install.log
        ) | sed ':a;N;$!ba;s/\n/<br>\n/g'
    )
    [ -d ${INSTALL_APP} ] && cp ${SCRIPTS_DIR}/install.log ${INSTALL_APP}
    return $ok
}

preinst ()
{
    # Installation wizard requirements
    #if [ "${SYNOPKG_PKG_STATUS}" != "UPGRADE" ] && [ ! -d "${wizard_download_dir}" ]; then
    #    exit 1
    #fi

    exit 0
}

postinst ()
{
    # Create user

    # Check system
    if [ "${SYNOPKG_PKG_STATUS}" != "UPGRADE" ]; then
        do_check || exit 1
    fi

    # Edit the configuration according to the wizard
    ( cd ${INSTALL_APP} ; ./synoboxi init )
    ( cd ${INSTALL_APP} ; [ -n "${wizard_port}" ] && ./synoboxi port "${wizard_port}" )
    ( cd ${INSTALL_APP} ; [ -n "${wizard_user}" ] && ./synoboxi user "${wizard_user}" )
    ( cd ${INSTALL_APP} ; [ -n "${wizard_pass}" ] && ./synoboxi pass "${wizard_pass}" )

    exit 0
}

#uninst are called on older scripts
preuninst ()
{
    # Stop
    ${SCRIPTS_DIR}/start-stop-status stop &> /dev/null

    # Remove the user (if not upgrading)
    if [ "${SYNOPKG_PKG_STATUS}" != "UPGRADE" ]; then
        ./busybox deluser ${USER}
    fi

    exit 0
}

#uninst are called on older scripts
postuninst ()
{
    exit 0
}

preupgrade ()
{
    # Stop
    ${SCRIPTS_DIR}/start-stop-status stop &> /dev/null

    # Revision 8 introduces backward incompatible changes
    OLD_VER=$( echo ${SYNOPKG_OLD_PKGVER} | sed -r "s/[^-]+-([^-]+).*/\1/" )
    if [ ${OLD_VER} -lt ${LAST_WIZARD_VER} ]; then
        echo "The <b>SynoBox</b> package must be uninstalled, as new settings need to be set during installation.<br><font color=red>Do not remove</font> <b>SynoBox Base</b> and <b>SynoBox Data</b> packages, otherwise all configuration will be lost."
        exit 1
    fi

    # Save some stuff
    rm -rf ${TMP_DIR}/${PACKAGE}
    mkdir -p ${TMP_DIR}/${PACKAGE}
    ( cd ${INSTALL_APP} ; [ -h var ] || tar cf ${TMP_DIR}/${PACKAGE}/var.tar var )

    exit 0
}

postupgrade ()
{
    # Restore some stuff
    #rm -rf ${INSTALL_DIR}/var
    ( cd ${INSTALL_APP} ; [ -h var ] || tar xpf ${TMP_DIR}/${PACKAGE}/var.tar )

    # Check system
    do_check || exit 1

    exit 0
}

