#!/bin/ash

PACKAGES="i-cloud i-manager homed-web homed-zigbee homed-automation mosquitto-nossl"
CONF_FILES="/etc/i-cloud.conf /etc/i-manager.conf /etc/homed/homed-web.conf /etc/homed/homed-zigbee.conf /etc/homed/homed-automation.conf"

# Проверяем доступность интернета
if ! ping -c 1 -W 5 8.8.8.8 >/dev/null 2>&1; then
    exit 0
fi

if ! ping -c 1 -W 5 8.8.8.8 >/dev/null 2>&1; then
    exit 0
fi

opkg update >/dev/null 2>&1

UPDATED_PACKAGES=""

for pkg in $PACKAGES; do
    installed_info=$(opkg list-installed | grep "^$pkg ")
    
    if [ -n "$installed_info" ]; then
        installed_version=$(echo "$installed_info" | awk '{print $3}')
        available_info=$(opkg list | grep "^$pkg ")
        available_version=$(echo "$available_info" | awk '{print $3}')
        
        if [ "$installed_version" != "$available_version" ]; then
            UPDATED_PACKAGES="$UPDATED_PACKAGES $pkg"
        fi
    else
        UPDATED_PACKAGES="$UPDATED_PACKAGES $pkg"
    fi
done

if [ -n "$UPDATED_PACKAGES" ]; then
    for conf in $CONF_FILES; do
        if [ -f "$conf" ]; then
            cp "$conf" "/tmp/$(basename $conf).backup"
        fi
    done
    
    for pkg in $UPDATED_PACKAGES; do
        if opkg list-installed | grep -q "^$pkg "; then
            opkg upgrade $pkg >/dev/null 2>&1
        else
            opkg install $pkg >/dev/null 2>&1
        fi
    done
    
    for conf in $CONF_FILES; do
        backup="/tmp/$(basename $conf).backup"
        if [ -f "$backup" ]; then
            cp "$backup" "$conf"
            rm "$backup"
        fi
        # Удаляем файлы -opkg созданные при обновлении
        if [ -f "${conf}-opkg" ]; then
            rm -f "${conf}-opkg"
        fi
    done
    
    # Если обновился homed-web — обновляем логотипы и title
    if echo "$UPDATED_PACKAGES" | grep -q "homed-web"; then
        rm -f /usr/share/homed-web/img/xmas.svg
        rm -f /usr/share/homed-web/img/homed.svg
        wget -q -O /usr/share/homed-web/img/xmas.svg https://opkg.vse-i.ru/deploy/xmas.svg >/dev/null 2>&1
        wget -q -O /usr/share/homed-web/img/homed.svg https://opkg.vse-i.ru/deploy/homed.svg >/dev/null 2>&1
        
        # Изменяем title в index.html
        if [ -f "/usr/share/homed-web/index.html" ]; then
            sed 's/<title>HOMEd<\/title>/<title>Контроллер И!<\/title>/' /usr/share/homed-web/index.html > /usr/share/homed-web/index.html.tmp && mv /usr/share/homed-web/index.html.tmp /usr/share/homed-web/index.html
        fi
    fi
    
fi
