#!/bin/sh

RUN_DIR="/tmp"
if [ -d "/tmpbox" ]; then
    RUN_DIR="/tmpbox"
fi

export LD_LIBRARY_PATH="$RUN_DIR/lib:$LD_LIBRARY_PATH:"

cd "$RUN_DIR"

chmod 777 web/images/*
chmod 777 web/css/*
chmod 777 web/js/*
chmod 777 web/*
chmod 777 ko/extdrv/*
chmod 777 ko/*
chmod 777 lib/*
chmod 777 *
chmod 777 samba/bin/*
chmod 777 dropbear/*

log2file_value=$(grep "^log2file:" "/box/box.ini" 2>/dev/null | cut -d ":" -f2 | tr -d '[:space:]')
if [ ! -z "$log2file_value" ] && [ "$log2file_value" != "0" ]; then
    LOG_DIR="/tmp/logs"
    CURRENT_LOG="$LOG_DIR/console_output.log"

    mkdir -p "$LOG_DIR"

    exec 1>>"$CURRENT_LOG"
    exec 2>>"$CURRENT_LOG"

    ./log_rotation &
fi

#trtc clog
rm -f /.cache/*.clog

edid_config=$(cat /box/box.ini | grep 'edid_index:')
edid=${edid_config#*:}
edid=$(echo $edid | tr -d '[:space:]')
edid_length=$(echo -n "$edid" | wc -c)
if [ "$edid_length" -eq 1 ] || [ "$edid_length" -eq 2 ]
then
    cp "$RUN_DIR"/edid/"$edid".* /tmp/edid.bin
    echo edid is index $edid
fi

CONFIG_FILE="/box/box.ini"

SAMBA_START=1
if [ -f "$CONFIG_FILE" ]; then
    samba_enable=$(grep "^samba_enable:" "$CONFIG_FILE" | cut -d ":" -f2 | tr -d '[:space:]')
    if [ ! -z "$samba_enable" ] && [ "$samba_enable" = "0" ]; then
        SAMBA_START=0
    fi
fi

cd "$RUN_DIR/ko"
./load524v100 -i

#telnetd&
#killall telnetd

if [ -x "$RUN_DIR/dropbear/run" ]; then
    "$RUN_DIR/dropbear/run" &
fi

#GPIO12_0 RESET
bspmm 0x10ff0100 0x1000

#GPIO12_3
bspmm 0x10ff010c 0x1200

#GPIO12_1 12_2 12_6 12_5
bspmm 0x10ff0104 0x1000
bspmm 0x10ff0108 0x1000
bspmm 0x10ff0118 0x1001
bspmm 0x10FF0114 0x1201

#GPIO12 DIR
bspmm 0x1109c400 0x76

#POWER ON
bspmm 0x1109c008 0x0

#LAN OFF
bspmm 0x1109c010 0x4

#HDMI OFF
bspmm 0x1109c100 0x40

#WIFI POWER ON
#bspmm 0x1109c080 0x0

#3u board not enable these
ethname=$(cat /sys/class/net/eth0/device/modalias | grep 'gmac')
if [[ -z $ethname ]]; then
    #SDI 20B/10B
    bspmm 0x10FF00F8 0x1001

    #GPIO1_0 RButton
    bspmm 0x102F0008 0x1200

    #GPIO0_4 RLED
    bspmm 0x102F002C 0x1200
    bspmm 0x11090040 0x10
fi

#UART1; unisheen 3u board don't enable Ethernet conflict
#bspmm 0x102F0044 0x1201
#bspmm 0x102F0048 0x1201

#UART2

#UART1 -> GPIO GPIO

#UART2 -> GPIO GPIO

echo 20480000 > /proc/sys/net/core/wmem_default
echo 40960000 > /proc/sys/net/core/wmem_max

mtu_config=$(cat /box/box.ini | grep 'mtu_size:')
mtu=${mtu_config:9}
mtu_size=`echo "$mtu" | wc -c`
if [ "$mtu_size" = "4" ] || [ "$mtu_size" = "5" ]
then
        ifconfig eth0 mtu $mtu
        echo mtu size is $mtu
fi

ifconfig lo up
if [ "$SAMBA_START" = "1" ]; then
    "$RUN_DIR/samba/bin/smbd" -D &
fi

cd "$RUN_DIR"
./tc qdisc replace dev eth0 root fq flow_limit 1000 limit 20000
./factory
./reset &
./box.ss524
