#!/bin/bash

set -e

if [[ "${is_minimal}" == "true" ]]; then
    return 0
elif [[ "${is_ghost}" == "true" ]]; then
    return 0
fi

# TODO, repeat code
### Install third-party software packages for local
do_third_party() {
    dirname=$1
    rsync -aHA ${dirname}/third-party/ /target/tmp/third-party/
    chroot /target /bin/sh -c 'find /tmp/third-party -name "*.deb" | grep -v "kylin-os-installer" >/tmp/third-party/packages.list' || true
    count=$(cat /target/tmp/third-party/packages.list | wc -l)
    if [ $count -ne 0 ]; then
        chroot /target /bin/sh -c 'unset DEBIAN_HAS_FRONTEND && UCF_FORCE_CONFFNEW=YES dpkg -i $(cat /tmp/third-party/packages.list | xargs)'
    fi
    rm -rf /target/tmp/third-party
}

install_package() {
    pkgdir=$1
    if [[ ! -d /target/tmp/third-party/${pkgdir} ]]; then
        return
    fi

    count=$(find /target/tmp/third-party/${pkgdir} -name "*.deb" | wc -l)

    if [ $count -ne 0 ]; then
        chroot /target /bin/sh -c "unset DEBIAN_HAS_FRONTEND && UCF_FORCE_CONFFNEW=YES dpkg -i /tmp/third-party/${pkgdir}/*.deb"
    fi
}

do_990third_party() {
    dirname=$1
    rsync -aHA ${dirname}/third-party/ /target/tmp/third-party/
    install_package "common"

    if [[ "${hw_typedata}" =~ "pguv" ]]; then
        install_package "pguv"
    elif [[ "${hw_typedata}" =~ "klvu" ]]; then
        install_package "klvu"
    elif [[ "${hw_typedata}" =~ "klvv" ]]; then
        install_package "klvv"
    elif [[ "${hw_typedata}" =~ "pguw" ]]; then
        install_package "pguw"
    elif [[ "${hw_typedata}" =~ "pangum900" ]]; then
        install_package "pangum900"
    fi

    rm -rf /target/tmp/third-party
}

if [[ -d /home/kylin/third-party ]]; then
   do_third_party "/home/kylin"
fi

### Install third-party software packages
if [[ -d /cdrom/third-party ]]; then
   if [[ "${is_990_9a0}" == true ]]; then
       do_990third_party "/cdrom"
   else
       do_third_party "/cdrom"
   fi
fi

third_party=$(get_value third-party)
if [[ -n ${third_party} ]]; then
#if grep -q "third-party=" /proc/cmdline; then
   if grep -q "url=" /proc/cmdline; then
           cmd_cfg=$(cat /proc/cmdline)
           url_ip=$(echo ${cmd_cfg##*url=}| awk '{print $1}')
           url_ip=${url_ip%/*}
	    
	    mkdir -p /target/third-party
           wget -P/target/third-party ${url_ip}/${third_party}
           tar -xf /target/third-party/${third_party} -C /target/third-party/
	    do_third_party "/target/third-party"
	    rm -rf /target/third-party
   fi
fi


