#!/bin/bash

SYSCONFCMD="/usr/bin/sysconf"
SYSCONF="/etc/speaker.conf"
VOLCONF="/oem/etc/volctrl.conf"

action="$1"

[ -z "${action}" ] && exit 0

case ${action} in
    set_cronreboot)
        CRON_DIR="/oem/etc/cron/crontabs"
        CRON_CONF="${CRON_DIR}/root"

        if [ ! -f "${CRON_CONF}" ];then
            if [ ! -d "${CRON_DIR}" ];then
                mkdir -p ${CRON_DIR}
            fi
            touch ${CRON_CONF}
            chmod 0600 ${CRON_CONF}
        fi

        CRON_STAT="`ps|grep crond|grep -v grep`"
        if [ -z "${CRON_STAT}" ];then
            /usr/sbin/crond -c ${CRON_DIR}
            sed -i '/check_log_size/d' ${CRON_CONF}
            echo "0 2 * * * /etc/scripts/shell_action.sh check_log_size" > ${CRON_CONF}
        fi

        enable="`${SYSCONFCMD} ${SYSCONF} get restart-timer enable`"
        if [ "foo${enable}" == "foono" ];then
            sed -i '/reboot/d' ${CRON_CONF}
            exit 0
        fi

        month="*"
        week="`${SYSCONFCMD} ${SYSCONF} get restart-timer week`"
        day="`${SYSCONFCMD} ${SYSCONF} get restart-timer day`"
        hour="`${SYSCONFCMD} ${SYSCONF} get restart-timer hour`"
        minutes="`${SYSCONFCMD} ${SYSCONF} get restart-timer minutes`"
        sed -i '/reboot/d' ${CRON_CONF}
        echo "${minutes} ${hour} ${day} ${month} ${week} /sbin/reboot" >> ${CRON_CONF}
        exit 0
    ;;

    getdeviceInfo)
        dev="eth1"

		model="`${SYSCONFCMD} ${SYSCONF} get system model`"
		hardVersion="`${SYSCONFCMD} ${SYSCONF} get system hard_version`"
		ip="`/sbin/ifconfig ${dev} | grep 'inet ' | awk '{print $2}'`"
		ipMode="`${SYSCONFCMD} ${SYSCONF} get system ip_assign`"
		mac="`/sbin/ifconfig ${dev} | grep ether | awk '{printf $2}' | tr a-z A-Z`"
		softwareVersion="`${SYSCONFCMD} ${SYSCONF} get system firmware`"
		submask="`/sbin/ifconfig ${dev} | grep netmask | awk '{print $4}'`"
        onvif_enable="`${SYSCONFCMD} ${SYSCONF} get onvif enable`"
        account_port1="`${SYSCONFCMD} ${SYSCONF} get account_info_1 port`"
        account_port2="`${SYSCONFCMD} ${SYSCONF} get account_info_2 port`"
        remark="`${SYSCONFCMD} ${SYSCONF} get system location`"
        multicast="`${SYSCONFCMD} ${SYSCONF} get multicast_player enable`"
		echo -n "${hardVersion}|${ip}|${ipMode}|${mac}|${softwareVersion}|${model}|${submask}|${onvif_enable}|${account_port1}|${account_port2}|${remark}|${multicast}"
	;;
	getconfigInfo)
        model="`${SYSCONFCMD} ${SYSCONF} get system model`"
        masterExten="`${SYSCONFCMD} ${SYSCONF} get account_info_1 username`"
        masterActivate="`${SYSCONFCMD} ${SYSCONF} get account_info_1 enable`"
        masterServer="`${SYSCONFCMD} ${SYSCONF} get account_info_1 server`"
        masterDomain="`${SYSCONFCMD} ${SYSCONF} get account_info_1 domain`"
        [ -z "${masterDomain}" ] && masterDomain=${masterServer}
        micVolume="`${SYSCONFCMD} ${VOLCONF} get volume volume_in`"
        speakerVolume="`${SYSCONFCMD} ${VOLCONF} get volume volume_out`"

        if [ "foo${masterActivate}" = "fooyes" ];then
            search_str="baresip-reg-status-${masterExten}-${masterDomain}"
            masterRegisterStatus="`/usr/sbin/redis-cli get ${search_str} | cut -d ',' -f2 | cut -d ':' -f2 | tr -d '}' | tr -d '\"'`"
        else
            masterRegisterStatus="unregister"
        fi

        echo -n "${masterExten}|${masterServer}|${masterRegisterStatus}|${speakerVolume}|${micVolume}"
	;;

	getStatus)
		STATUSDIR="/oem/.onvif_upgrade"
		STATUSPATH="${STATUSDIR}/status"
		[ ! -d "${STATUSDIR}" ] && mkdir -p ${STATUSDIR} && echo -n "UpgradePre" > ${STATUSPATH}
		cat ${STATUSPATH}
		exit 0
	;;

	addRoute)
		dstIp="$2"	
		[ -z "${dstIp}" ] && exit 0

        dev="eth1"

		if ! /sbin/route -n | grep "${dstIp}" > /dev/null;then
			/sbin/route add -net ${dstIp} netmask 255.255.255.255 dev ${dev}
		fi
		exit 0
	;;

	delRoute)
		dstIp="$2"	
		[ -z "${dstIp}" ] && exit 0

        dev="eth1"

		if /sbin/route -n | grep "${dstIp}" > /dev/null;then
			/sbin/route del -net ${dstIp} netmask 255.255.255.255 dev ${dev}
		fi
		exit 0
	;;

    rebootIpc)
        /usr/bin/curl --connect-timeout 1 -X GET "http://10.231.132.139/cgi-bin/web.cgi?action=reboot&cmd=system&username=admin&password=33e97a6101dce4c3ad589754e79b14adacc52d45"
        exit 0
    ;;

    rebootIpcAndReboot)
        $0 showReboot
        $0 rebootIpc
        sleep 1
        /sbin/reboot
        exit 0
    ;;

    setOnvifVol)
        volume=${2}
        /usr/sbin/redis-cli PUBLISH volume-value-channel "{\"onvif_volume\": ${volume}}"
        ${SYSCONFCMD} ${VOLCONF} set volume onvif_volume ${volume}
    ;;

    startSyncTimeToIPAC)
        $0 stopSyncTime
        if [ ! -z "$2" ];then
            delay=$2
        else
            delay=""
        fi
        server="`${SYSCONFCMD} ${SYSCONF} get account_info_1 server`"
        model="`${SYSCONFCMD} ${SYSCONF} get system model`"
        interface="eth1"

        if [ ! -z ${delay} ];then
            /usr/sbin/ptpd2 -i ${interface} -s -U -g --ptpengine:log_delayreq_interval=1 --delay-override ${delay} -u ${server}
        else
            /usr/sbin/ptpd2 -i ${interface} -s -U -g --ptpengine:log_delayreq_interval=1 -u ${server}
        fi

        exit 0
    ;;

    startSyncTimeToPtpServer)
        $0 stopSyncTime
        enable="`${SYSCONFCMD} ${SYSCONF} get ptp enable`"
        if [ "foo${enable}" = "fooyes" ];then
            if [ ! -z "$2" ];then
                delay=$2
            else
                delay=""
            fi

            server="`${SYSCONFCMD} ${SYSCONF} get ptp server`"
            model="`${SYSCONFCMD} ${SYSCONF} get system model`"
            interface="eth1"
            if [ ! -z ${delay} ];then
                /usr/sbin/ptpd2 -i ${interface} -s -U -g --ptpengine:log_delayreq_interval=1 --delay-override ${delay} -u ${server}
            else
                /usr/sbin/ptpd2 -i ${interface} -s -U -g --ptpengine:log_delayreq_interval=1 -u ${server}
            fi
        fi

        exit 0
    ;;

    stopSyncTime)
        pid="`cat /var/run/ptpd2.lock | tr -d ' '`"
        if [ ! -z "${pid}" ];then
            /bin/kill -9  ${pid} > /dev/null 2>&1
        fi
        exit 0
    ;;

    set_sshd)
        /etc/init.d/S50sshd restart
    ;;

    ai)
        case $2 in
            start)
                enAIAgent="`${SYSCONFCMD} ${SYSCONF} get ai_settings enable`"
                if [ "${enAIAgent}" = "yes" ];then
                    tmp_hard_verssion="`/usr/bin/vendor_storage -r VENDOR_WIFI_MAC_ID | awk -F" " '{print $2}'`"
                    hard_version=${tmp_hard_verssion: -2}
                    if [ "${hard_version}" = "32" ];then
                        echo 1 > /sys/class/gpio/gpio143/value
                    else
                        echo 1 > /sys/class/gpio/gpio134/value
                    fi
                    /etc/scripts/serial_ctrl &
                fi
            ;;
            stop)
                killall serial_ctrl > /dev/null 2>&1
                tmp_hard_verssion="`/usr/bin/vendor_storage -r VENDOR_WIFI_MAC_ID | awk -F" " '{print $2}'`"
                hard_version=${tmp_hard_verssion: -2}
                if [ "${hard_version}" = "32" ];then
                    echo 0 > /sys/class/gpio/gpio143/value
                else
                    echo 0 > /sys/class/gpio/gpio134/value
                fi
            ;;
            restart)
                $0 ai stop
                $0 ai start
            ;;
        esac

    ;;

    set_onvif)
        generate_config() {
            dev="eth1"

            model="`${SYSCONFCMD} ${SYSCONF} get system model`"
            hardVersion="`${SYSCONFCMD} ${SYSCONF} get system hard_version`"
            ip="`/sbin/ifconfig ${dev} | grep 'inet ' | awk '{print $2}'`"
            mac="`/sbin/ifconfig ${dev} | grep ether | awk '{printf $2}' | sed 's/:/-/g'`"
            softwareVersion="`${SYSCONFCMD} ${SYSCONF} get system firmware`"
            Manufacturer="G2"
            username="`${SYSCONFCMD} ${SYSCONF} get onvif username`"
            password="`${SYSCONFCMD} ${SYSCONF} get onvif password`"
            enMIC="`${SYSCONFCMD} ${SYSCONF} get onvif enable_mic`"
            mode="`${SYSCONFCMD} ${SYSCONF} get onvif mode`"
            SerialNumber="`cat /proc/cpuinfo | grep Serial | awk '{print $3}'`"
            uuid="`cat /tmp/uuid`"
            Mode="`${SYSCONFCMD} ${SYSCONF} get onvif relay_mode`"
            DelayTime="`${SYSCONFCMD} ${SYSCONF} get onvif relay_delaytime`"
            Type="`${SYSCONFCMD} ${SYSCONF} get onvif relay_type`"
            case ${mode} in
                1)
                    quality=4
                    fps=15
                    bitrate=96
                    auth=1
                ;;
                2|8)
                    quality=5
                    fps=30
                    bitrate=160
                    auth=1
                ;;
                10)
                    quality=3
                    fps=5
                    bitrate=64
                    auth=2
                ;;
                *)
                    quality=3
                    fps=5
                    bitrate=64
                    auth=1
                ;;
            esac

            config="/oem/etc/config.xml"
            [ ! -f ${config} ] && touch ${config}
            cat << END > ${config}
<?xml version="1.0" encoding="utf-8"?>
<config>
	<server_ip>${ip}</server_ip>
	<server_port>8000</server_port>
	<need_auth>${auth}</need_auth>
	<auth_user>${username}</auth_user>
	<auth_pass>${password}</auth_pass>
	<discoverable>1</discoverable>
	<merge_source>1</merge_source>
	<information>
		<Manufacturer>${Manufacturer}</Manufacturer>
		<Model>${model}</Model>
		<FirmwareVersion>${softwareVersion}</FirmwareVersion>
		<SerialNumber>${SerialNumber}</SerialNumber>
		<HardwareId>${hardVersion}</HardwareId>
		<UUId>${uuid}</UUId>
	</information>
	<video_source_config>
		<x min="0" max="100" />
		<y min="0" max="100" />
		<width min="320" max="1280" />
		<height min="240" max="720" />
	</video_source_config>
	<profile>
		<video_source>
			<width>640</width>
			<height>480</height>
		</video_source>
		<video_encoder>
			<width>640</width>
			<height>480</height>
			<quality>${quality}</quality>
			<session_timeout>10</session_timeout>
			<framerate>${fps}</framerate>
			<encoding_interval>1</encoding_interval>
			<bitrate_limit>${bitrate}</bitrate_limit>
			<encoding>H264</encoding>
			<h264>
				<gov_length>20</gov_length>
				<h264_profile>Main</h264_profile>
			</h264>
		</video_encoder>
		<audio_output></audio_output>
		<audio_decoder>
			<sample_rate>8</sample_rate>
			<decoding>PCMU</decoding>
		</audio_decoder>
END
if [ "foo${enMIC}" = "fooyes" ];then
        cat << END >> ${config}
		<audio_source></audio_source>
		<audio_encoder>
			<session_timeout>10</session_timeout>
			<sample_rate>8</sample_rate>
			<bitrate>64</bitrate>
			<encoding>PCMU</encoding>
		</audio_encoder>
END
fi
        cat << END >> ${config}
		<relay_output>
			<mode>${Mode}</mode>
			<delaytime>${DelayTime}</delaytime>
			<idlestate>closed</idlestate>
			<tpye>${Type}</tpye>
		</relay_output>
		<stream_uri>rtsp://${ip}:554/MainStream</stream_uri>
	</profile>
	<scope_fixed>onvif://www.onvif.org/Profile/Streaming</scope_fixed>
	<scope_fixed>onvif://www.onvif.org/location/country/china</scope_fixed>
	<scope_fixed>onvif://www.onvif.org/type/video_encoder</scope_fixed>
	<scope_fixed>onvif://www.onvif.org/type/audio_decoder</scope_fixed>
	<scope_fixed>onvif://www.onvif.org/name/IPSPEAKER</scope_fixed>
	<scope_fixed>onvif://www.onvif.org/hardware/${model}</scope_fixed>
	<scope_config>onvif://www.onvif.org/acc/uuid/${uuid}</scope_config>
	<scope_config>onvif://www.onvif.org/acc/mac/${mac}</scope_config>
	<event>
		<renew_interval>60</renew_interval>
		<simulate_enable>0</simulate_enable>
		<simulate_interval>10</simulate_interval>
	</event>
</config>
END
            sync
        }

        #生成配置文件
        generate_config
        enable="`${SYSCONFCMD} ${SYSCONF} get onvif enable`"
        if [ "foo${enable}" = "fooyes" ];then
            killall onvifserver > /dev/null 2>&1
            killall rtspserver > /dev/null 2>&1
            /etc/scripts/rtspserver > /dev/null 2>&1 &
            sleep 1
            /etc/scripts/onvifserver > /dev/null 2>&1 &
        else
            killall onvifserver > /dev/null 2>&1
            killall rtspserver > /dev/null 2>&1
        fi
        exit 0
    ;;

    check_log_size)
        cdr_log_file="/userdata/cdr.csv"
        operation_log_file="/userdata/system.csv"
        max_line=20000
        remain_line=10000
        total_lines=$(wc -l < "$cdr_log_file")
        end_delelte_line=$((total_lines - remain_line))
        if ((total_lines > max_line)); then
            sed -i '1,'"$end_delelte_line"'d' "$cdr_log_file"
        fi

        total_lines=$(wc -l < "$operation_log_file")
        end_delelte_line=$((total_lines - remain_line))
        if ((total_lines > max_line)); then
            redis-cli LPUSH writelog-channel "log_clean"
            sed -i '1,'"$end_delelte_line"'d' "$operation_log_file"
        fi
    ;;

    set_python_priority)
        sleep 3
        pid="`ps | grep ispeaker | grep -v grep | awk -F' ' '{print $1}'`"

        if [ "foo${pid}" != "foo" ];then
            loop=5
            while [ $loop -gt 0 ]
            do
                echo "-1000" > /proc/${pid}/oom_score_adj
                loop="`expr $loop - 1`"
                usleep 200000
            done
        fi

        exit 0
    ;;

    showReboot)
        /usr/bin/curl --connect-timeout 2 http://127.0.0.1/api/show-start > /dev/null 2>&1 &
        exit 0
    ;;

    *)
        exit 0
    ;;
esac