#!/bin/sh

# Package
PACKAGE="owfs"
DNAME="OWFS"

# Others
INSTALL_DIR="/usr/local/${PACKAGE}"
SSS="/var/packages/${PACKAGE}/scripts/start-stop-status"
PATH="${INSTALL_DIR}/bin:/usr/local/bin:/bin:/usr/bin:/usr/syno/bin"
USER="root"
CFG_FILE="${INSTALL_DIR}/var/owfs.conf"
CGI_FILE="${INSTALL_DIR}/app/owfs.cgi"
TMP_DIR="${SYNOPKG_PKGDEST}/../../@tmp"


preinst ()
{
    exit 0
}

postinst ()
{
    # Link
    ln -s ${SYNOPKG_PKGDEST} ${INSTALL_DIR}

    # Put owfiles in the PATH
    mkdir -p /usr/local/bin
    ln -s ${INSTALL_DIR}/bin/owdir /usr/local/bin/owdir
    ln -s ${INSTALL_DIR}/bin/owexist /usr/local/bin/owexists
    ln -s ${INSTALL_DIR}/bin/owexternal /usr/local/bin/owexternal
    ln -s ${INSTALL_DIR}/bin/owftpd /usr/local/bin/owftpd
    ln -s ${INSTALL_DIR}/bin/owget /usr/local/bin/owget
    ln -s ${INSTALL_DIR}/bin/owhttpd /usr/local/bin/owhttpd
    ln -s ${INSTALL_DIR}/bin/owpresent /usr/local/bin/owpresent
    ln -s ${INSTALL_DIR}/bin/owread /usr/local/bin/owread
    ln -s ${INSTALL_DIR}/bin/owserver /usr/local/bin/owserver
    ln -s ${INSTALL_DIR}/bin/owwrite /usr/local/bin/owwrite

    # Edit the configuration according to the wizzard
    sed -i -e "s|@server_port@|${wizard_owserver_port:=4304}|g" ${CFG_FILE}
    sed -i -e "s|@httpd_port@|${wizard_owhttpd_port:=3001}|g" ${CFG_FILE}
    sed -i -e "s|@httpd_port@|${wizard_owhttpd_port:=3001}|g" ${CGI_FILE}
    if [ ! -z ${wizard_device_usb} ]; then
        sed -i -e "s|@device@|usb|g" ${CFG_FILE}
    else
        sed -i -e "s|@device@|device = ${wizard_device_serial:=/dev/ttyS0}|g" ${CFG_FILE}
    fi

    # Correct the files ownership
    chown -R ${USER}:root ${SYNOPKG_PKGDEST}

    exit 0
}

preuninst ()
{
    # Stop the package
    ${SSS} stop > /dev/null

    exit 0
}

postuninst ()
{
    # Remove link
    rm -f ${INSTALL_DIR}
    rm -f /usr/local/bin/owdir
    rm -f /usr/local/bin/owexists
    rm -f /usr/local/bin/owexternal
    rm -f /usr/local/bin/owftpd
    rm -f /usr/local/bin/owget
    rm -f /usr/local/bin/owhttpd
    rm -f /usr/local/bin/owpresent
    rm -f /usr/local/bin/owread
    rm -f /usr/local/bin/owserver
    rm -f /usr/local/bin/owwrite

    exit 0
}

preupgrade ()
{
    # Stop the package
    ${SSS} stop > /dev/null

    # Save some stuff
    rm -fr ${TMP_DIR}/${PACKAGE}
    mkdir -p ${TMP_DIR}/${PACKAGE}
    mv ${INSTALL_DIR}/var ${TMP_DIR}/${PACKAGE}/

    exit 0
}

postupgrade ()
{
    # Restore some stuff
    rm -fr ${INSTALL_DIR}/var
    mv ${TMP_DIR}/${PACKAGE}/var ${INSTALL_DIR}/
    rm -fr ${TMP_DIR}/${PACKAGE}

    exit 0
}
