#!/bin/bash

skin="Kucat"

is_x86_64() {
    DISTRIB_ARCH=$(cat /etc/openwrt_release | grep "DISTRIB_ARCH" | cut -d "'" -f 2)
    if [ "$DISTRIB_ARCH" = "x86_64" ]; then
        return 0
    else
        return 1
    fi
}

remove_check_signature() {
    local opkg_conf="/etc/opkg.conf"
    sed -i '/option check_signature/d' "$opkg_conf"
}

is_iStore() {
    [ -s "/www/luci-static/istore/index.js" ] && return 0  || return 1
}

is_vip() {
    local ezver
    ezver=$(grep -o "EZVER=\S*" /etc/ezopenwrt_version 2>/dev/null | cut -d'-' -f3)
    [[ "${ezver^^}" =~ VIP ]]
}

istore_install(){
    if is_iStore; then
        echo "已存在有iStore应用商店,无须再安装！"
     else
       echo "正在安装iStore应用商店...."
	remove_check_signature
        opkg update
        opkg remove git-lfs
        setup_software_source 1
	ISTORE_REPO=https://istore.linkease.com/repo/all/store
	FCURL="curl --fail --show-error"

	IPK=$($FCURL "$ISTORE_REPO/Packages.gz" | zcat | grep -m1 '^Filename: luci-app-store.*\.ipk$' | sed -n -e 's/^Filename: \(.\+\)$/\1/p')
	[ -n "$IPK" ] || exit 1
	$FCURL "$ISTORE_REPO/$IPK" | tar -xzO ./data.tar.gz | tar -xzO ./bin/is-opkg >/tmp/is-opkg
	chmod 755 /tmp/is-opkg
	

	/tmp/is-opkg update
	/tmp/is-opkg install taskd
	/tmp/is-opkg opkg install --force-reinstall luci-lib-taskd luci-lib-xterm
	/tmp/is-opkg opkg install --force-reinstall luci-app-store || exit $?
	[ -s "/etc/init.d/tasks" ] || /tmp/is-opkg opkg install --force-reinstall taskd
	[ -s "/usr/lib/lua/luci/cbi.lua" ] || /tmp/is-opkg opkg install luci-compat >/dev/null 2>&1

	sed -i 's/istore.linkease.com/istore.istoreos.com/g' /bin/is-opkg

	sed -i 's/istore.linkease.com/istore.istoreos.com/g' /etc/opkg/compatfeeds.conf
	sed -i 's/istore.linkease.com/istore.istoreos.com/g' /www/luci-static/istore/index.js

        uci -q set luci.main.mediaurlbase='/luci-static/kucat'
        uci commit
	rm -rf /tmp/is-opkg /tmp/luci*
        echo "iStore应用商店安装完成！"
    fi
    exit
}

drv_install(){
    if is_vip; then
        bash /etc/kmodreg drv 
    else
         echo "目前此功能仅限VIP版本提供！"
    fi
    exit
}

docker_install(){
    if is_vip; then
        bash /etc/kmodreg docker
    else
        echo "目前此功能仅限VIP版本提供！"
    fi
    exit
}

case "$1" in
    "istore") 
        istore_install
	;;  
    "drv") 
        drv_install
	;;  
    "docker") 
        docker_install
	;;  
    esac