#!/bin/sh
#wget -O - http://aquaplace.co.uk:8088/install_cpe.sh | sh 
SERVER="http://192.168.10.103"

download()
{
    FILE="$1"

    echo "Downloading $FILE"

    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$SERVER/$FILE" -o "/opt/$FILE"
    else
        wget -q -O "/opt/$FILE" "$SERVER/$FILE"
    fi
}

detect_os()
{
    if command -v ba-cli >/dev/null 2>&1; then
        echo "RDK"
        return
    fi

    if command -v uci >/dev/null 2>&1; then
        echo "OpenWRT"
        return
    fi

    echo "UNKNOWN"
}

echo "Installing CPE Agent"

mkdir -p /opt

download cpe-agent.sh
download cpe-agent-start.sh
download SSHServer_Private

# Dropbear key optional
if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$SERVER/SSHServer_Private.dropbear" \
        -o /opt/SSHServer_Private.dropbear 2>/dev/null
else
    wget -q -O /opt/SSHServer_Private.dropbear \
        "$SERVER/SSHServer_Private.dropbear" 2>/dev/null
fi

chmod +x /opt/cpe-agent.sh
chmod +x /opt/cpe-agent-start.sh

chmod 600 /opt/SSHServer_Private 2>/dev/null
chmod 600 /opt/SSHServer_Private.dropbear 2>/dev/null

OS="$(detect_os)"

echo "Detected OS: $OS"

case "$OS" in

    OpenWRT)

		echo "Configuring OpenWRT"

		for SECTION in $(uci show dropbear 2>/dev/null | awk -F'.' '/=dropbear/ {print $2}' | awk -F= '{print $1}')
		do
			CURRENT="$(uci get dropbear.${SECTION}.AllowLocalForwarding 2>/dev/null)"

			if [ "$CURRENT" != "1" ]; then
				echo "Enabling dropbear.${SECTION}.AllowLocalForwarding"

				uci set dropbear.${SECTION}.AllowLocalForwarding='1'
			fi
		done

		uci commit dropbear
		/etc/init.d/dropbear restart

        if ! grep -q "cpe-agent.sh" /etc/rc.local 2>/dev/null; then

            cp /etc/rc.local /tmp/rc.local.$$ 2>/dev/null

            sed '/^exit 0$/d' /etc/rc.local > /tmp/rc.local.$$ 2>/dev/null

            cat >> /tmp/rc.local.$$ <<'EOF'

(
    cd /opt
    sh /opt/cpe-agent.sh >> /tmp/cpe-agent.log 2>&1
) &

exit 0
EOF

            cp /tmp/rc.local.$$ /etc/rc.local
            chmod +x /etc/rc.local
        fi

        killall cpe-agent.sh 2>/dev/null

        (
            cd /opt
            sh /opt/cpe-agent.sh >> /tmp/cpe-agent.log 2>&1
        ) &
        ;;

    RDK)

        echo "Configuring RDK"

        systemctl stop cpe-agent 2>/dev/null

        systemd-run \
            --unit=cpe-agent \
            --working-directory=/opt \
            /bin/sh /opt/cpe-agent.sh

        sleep 2

        systemctl status cpe-agent --no-pager
        ;;

    *)

        echo "Unsupported platform"
        exit 1
        ;;
esac

echo
echo "Installation complete"
