#!/bin/sh -e
# Set Paths


# Tee command - borrowed from http://www.gnu.org/manual/gawk/html_node/Tee-Program.html
# 'Arnold Robbins, arnold@gnu.org, Public Domain 'and tweaked a bit.
TEE() {
    awk '
BEGIN {
  append=(ARGV[1] == "-a")
  for(i=append+1 ; i<ARGC;i++) {
      copy[i]=ARGV[i]
      if (append == 0) printf "" > copy[i];
  }
  ARGC=1; #Force stdin

}


{
    sub(/.*/,""); #remove chars in unrar output
    print ; 
    for (i in copy) { 
        print >> copy[i];
    }
    system(""); # Flush all buffers
    #fflush("");
}
END { for (i in copy) close(copy[i]) }
      ' "$@"
}

load_config() {
    CONF_FILE="$OVS_HOME/conf/$1.cfg"
    DEFAULTS_FILE="$OVS_HOME/conf/.$1.cfg.defaults"

    if [ ! -f "$CONF_FILE" ] ; then
        if [ ! -f "$CONF_FILE.example" ] ; then
            cp "$DEFAULTS_FILE" "$CONF_FILE.example"
        fi
        cp "$CONF_FILE.example" "$CONF_FILE"
    fi

    set -a
    set +e #ignore errors

    if [ -f "$DEFAULTS_FILE" ]; then
        dos2unix "$DEFAULTS_FILE" 2>/dev/null || true # fix for notepad users
        . "$DEFAULTS_FILE"
    fi
    if [ -f "$CONF_FILE" ]; then
        dos2unix "$CONF_FILE" 2>/dev/null || true # fix for notepad users
        . "$CONF_FILE"
    fi
    set +a
}

# reconstruct quoted argument list
arg_list() {
    local escaped_quote="'\\''"
    ARG_LIST=""
    for i in "$@" ; do
        ARG_LIST="$ARG_LIST '${i//\'/$escaped_quote}'" 
    done
    echo "$ARG_LIST"
}

export arg_list

archive() {
    # some browser/zip tool combos on windows dont like plain gz files.
    local d="`dirname "$1"`";
    local f="`basename "$1"`";

    #tgz simple to open via browser->zip program->editor
    #( cd "$d" && tar czf "$f.tgz" "$f" && rm "$f" )

    #gz -> Broswer can unzip but slower for some reason. Doesnt work great with IE?
    ( cd "$d" && gzip "$f" )
}
export archive


package_check() {
    local package="$1"
    local cmd="$2"
    local option="$3"
    local expect="$4"
    local verbose="${5:-}"
    if "$cmd" "$option" 2>&1 | grep -i -q "$expect" ; then
        export OVS_DEPEND_${package}_STATUS=0
    else
        export OVS_DEPEND_${package}_STATUS=1
        if [ -n "$verbose" ] ; then
            "$cmd" "$option" 2>&1 || true
            echo "Package $package failed. [$expect] not found in [$cmd $option] path=[$PATH] [$LD_LIBRARY_PATH]."
        fi
    fi
}
package_mandatory() {
    package_check GAWK gawk -V GNU 1
    package_check ICONV iconv -h Usage 1
    package_check WGET wget -h GNU 1
}
package_optional() {
    package_check LIBJPEG djpeg -h usage
    package_check NETPBM pnmscalefixed -h option
}

# Check if file has been loaded, but always reload if launched from unpak.sh
# This is in case nzbget itself has been started as a long running process under this environment.
# we want to make sure it picks up latest configuration when post processing is launched.
if [ -z "${OVS_ENV_SET:-}" -o "${0/unpak.sh/}" != "$0" ] ; then

    export OVS_ENV_SET=1


    # Find install folder.
    # Script may be source in which case $0 is wrong - use $BASH_SOURCE
    # But BASH_SOURCE might not be supported - on nmt

    EXE="${BASH_SOURCE:-}"
    if [ -z "$EXE" ] ; then
        # look for any file this process has open called ovsenv
        EXE="`ls -l /proc/$$/fd 2>/dev/null | awk '/ovsenv$/ { sub(/.* -> /,"") ; print }' `"
    fi

    while [ -h "$EXE" ] ; do EXE="$(readlink "$EXE")"; done
    OVS_HOME="$( cd "$( dirname "$EXE" )"/.. && pwd )"

    FAMILY=
    ARCH=

    if [ -f /mnt/syb8634/VERSION  ] ; then
        FAMILY=nmt
        ARCH=nmt100
        NMT_APP_DIR=/mnt/syb8634
    else
        if grep -q -- '-4[0-9][0-9]$' /nmt/apps/VERSION 2>/dev/null ; then
            FAMILY=nmt
            ARCH=nmt200
            NMT_APP_DIR=/nmt/apps
        else
            if [ -d /ffp/bin ] ; then
                FAMILY=funplug
                ARCH=funplug
            fi
        fi
    fi

    if [ -z "$ARCH" ] ; then
        FAMILY=pc
        ARCH=pc
    fi

    uid=`id -u -n`
    gid=`id -g`
    OVS_TMP=/tmp

    LD_LIBRARY_PATH="${LD_LIBRARY_PATH:-}"

    os_version=`cat /proc/version`

    nmt_version=

    PATH="$OVS_HOME/bin:$PATH"
    case "${FAMILY:-}" in
        nmt)
            uid=nmt
            gid=nmt

            ############################################################
            # Binaries for nmt platform
            #
            # The default firmware on nmt has an old version of busybox with many commands
            # that are either buggy or have missing options.
            # For this reason OVersight is bundled with a newer busybox.
            # However enve then some commands need all fetures of the GNU versions.
            #
            # 
            # ------------
            # wget : needs gnu - note nmt have their own version of gnu wget - this is buggy
            # find : new busybox - fails silently with -mtime -newer switches.
            # gunzip : needs gnu to handle passthru of uncompressed data (when retrieving html)
            ##############################################################

            PATH="$OVS_HOME/bin/$ARCH:$NMT_APP_DIR/bin:$PATH"
            LD_LIBRARY_PATH="$OVS_HOME/bin/$ARCH:$LD_LIBRARY_PATH"
            nmt_version=`grep . /???/*/VERSION`

            # on 100 series permissions are not set properly on all executables.
            # But we might be invoked as nobody - so make executable copies
            for i in unrar par2 ; do
                e_from="$NMT_APP_DIR/bin/$i" 
                e_to="$OVS_HOME/bin/$ARCH/$i"
                if [ -e "$e_from" -a ! -x "$e_from" -a ! -x "$e_to" ] ; then
                    cp "$e_from" "$e_to" && chmod 775 "$e_to"
                fi
            done

            if [ -d /share/Apps/local/bin ] ; then
                PATH="/share/Apps/local/bin:$PATH"
            fi
            if [ -d /share/bin ] ; then
                PATH="/share/bin:$PATH"
            fi
            for i in sort find ls tr dirname basename readlink wc sed dos2unix gzip tee ; do
                if [ ! -e "$OVS_HOME/bin/$ARCH/$i" ] ; then
                    ( cd "$OVS_HOME/bin/$ARCH" && ln -sf busybox "$i" )
                fi
            done

            if [ ! -e "$OVS_HOME/bin/$ARCH/libiconv.so.2" ] ; then
                (cd "$OVS_HOME/bin/$ARCH" && ln -sf libiconv.so.2.5.0 libiconv.so.2.5 && ln -sf libiconv.so.2.5 libiconv.so.2 )
            fi

            OVS_TMP="$OVS_HOME/tmp"
            chmod 777 "$OVS_HOME/logs" "$OVS_HOME/cache" || true # for Oversight running as Apache/nobody
        ;;
        funplug)
            uid=nobody
            gid=501
            #Odd error where globbing sometimes doesnt work when scripts called from awk
            #eg system("mv blah/*"); 
            #but always works from command line.
            #see if SHELL fixes.
            export SHELL=/ffp/bin/bash
            OVS_TMP="$OVS_HOME/tmp"
        ;;
        *)
            #optware
            if [ -d /opt/etc/init.d -a -d /opt/bin ] ; then
                case "$PATH" in
                    */opt/bin*) ;;
                    *)
                        PATH="/opt/bin:$PATH" 
                        OVS_TMP="$OVS_HOME/tmp"
                    ;;
                esac
            fi
            ;;
    esac

    #embedded platforms may have small /tmp partitions 
    if [ ! -d "$OVS_TMP" ] ; then
        mkdir -p "$OVS_TMP" || true
        chmod -R 777 "$OVS_TMP" || true
        if [ "`id -u -n`" = root ] ; then
            chown -R $uid:$gid "$OVS_TMP" || true
        fi
    fi

    export nmt_version os_version uid gid FAMILY ARCH OVS_HOME PATH LD_LIBRARY_PATH OVS_TMP
    export OVERSIGHT_ID="$uid:$gid"

    load_config unpak
    load_config catalog

    package_mandatory
    package_optional


fi

