#!/bin/ash

# Способы передачи токена:
# 1. TOKEN=your_token wget -O - http://gillopa.ru/deploy.sh | sh
# 2. wget -O - http://gillopa.ru/deploy.sh | sh -s your_token
# 3. wget -O - http://gillopa.ru/deploy.sh | sh (интерактивный ввод)

REF_CONFIG='
[log]
enabled=false
file=/var/log/homed.log

[mqtt]
host=localhost
port=1883
prefix=i
names=false

[default]
discovery=true
cloud=true

[device]
database=/opt/homed-zigbee/database.json
properties=/opt/homed-zigbee/properties.json
options=/opt/homed-zigbee/options.json
external=/opt/homed-zigbee/external
library=/usr/share/homed-zigbee
join=disabled

[gpio]
status=/sys/class/leds/status/brightness
boot=/sys/class/gpio/cc-boot/value
reset=/sys/class/gpio/cc-reset/value

[zigbee]
adapter=znp
port=/dev/ttyS1
baudrate=115200
panid=
channel=11
reset=gpio
power=5
write=true

[security]
key=0x000102030405060708090a0b0c0d0e0f

[debug]
port=false
adapter=false
zigbee=false
'

PACKAGES="i-cloud i-manager homed-web homed-zigbee homed-automation homed-custom homed-modbus"
SERVICES="i-manager homed-web homed-zigbee homed-automation i-cloud homed-custom homed-modbus"

check_package() {
    pkg=$1
    if opkg list-installed | grep -q "^$pkg -"; then
        echo "[+] Package $pkg is installed / Пакет $pkg установлен"
        return 0
    else
        echo "[-] Package $pkg is NOT installed / Пакет $pkg НЕ установлен"
        return 1
    fi
}

restart_services() {
    for service in $SERVICES; do
        if [ -f "/etc/init.d/$service" ]; then
            service $service restart
        fi
    done
}

setup_auto_update() {
    echo "Setting up auto-update system... / Настройка системы автообновления..."
    
    # Создаем init.d скрипт с встроенной логикой обновления
    cat > /etc/init.d/auto-update << 'EOF'
#!/bin/ash /etc/rc.common

START=99
STOP=10

start() {
    # Записываем в лог, что сервис запустился
    echo "$(date): auto-update service started" >> /tmp/auto-update.log
    
    # Запускаем обновление в фоне с задержкой
    (sleep 30 && {
        echo "$(date): starting update check" >> /tmp/auto-update.log
        # Ждем готовности интернета (до 5 попыток)
        for i in 1 2 3 4 5; do
            echo "$(date): ping attempt $i" >> /tmp/auto-update.log
            if ping -c 1 8.8.8.8 >/dev/null 2>&1; then
                echo "$(date): internet available, downloading update" >> /tmp/auto-update.log
                # Сначала проверим, что можем загрузить скрипт
                if wget -O /tmp/update.sh "https://opkg.vse-i.ru/deploy/update.sh" 2>>/tmp/auto-update.log; then
                    echo "$(date): update script downloaded successfully" >> /tmp/auto-update.log
                    echo "$(date): executing update script" >> /tmp/auto-update.log
                    sh /tmp/update.sh >> /tmp/auto-update.log 2>&1
                    echo "$(date): update script execution completed" >> /tmp/auto-update.log
                    rm -f /tmp/update.sh
                else
                    echo "$(date): failed to download update script" >> /tmp/auto-update.log
                fi
                echo "$(date): update completed" >> /tmp/auto-update.log
                break
            fi
            sleep 30
        done
        echo "$(date): update check finished" >> /tmp/auto-update.log
    }) &
}

stop() {
    return 0
}
EOF

    chmod +x /etc/init.d/auto-update
    /etc/init.d/auto-update enable
    
    # Проверяем, что сервис включен
    if /etc/init.d/auto-update enabled; then
        echo "Сервис auto-update включен для автозапуска"
    else
        echo "Команда enable не сработала, создаем симлинк вручную"
        ln -sf /etc/init.d/auto-update /etc/rc.d/S99auto-update
        echo "Симлинк создан вручную"
    fi
    
    echo "Система автообновления настроена:"
    echo "- Сервис auto-update создан и включен"
    echo "- Логи /tmp/auto-update.log"
}

opkg update

for pkg in $PACKAGES; do
    opkg install $pkg
done

mkdir -p /etc/homed

# Проброс i-manager в homed среду
service homed-custom stop
mkdir -p /opt/homed-custom
echo '{"devices": [{"active": true,"bindings": {"status": {"inPattern": "{{ on if json.water == true else off }}","inTopic": "i/status/manager","outPattern": "{\"action\": \"setWater\", \"enabled\": {{ true if value == on else false }}}","outTopic": "i/command/manager"}},"cloud": false,"discovery": false,"exposes": ["switch"],"id": "manager_2","name": "Вода","options": {"retain": true},"real": true},{"active": true,"bindings": {"status": {"inPattern": "{{ off }}","inTopic": "i/status/manager","outPattern": "{\"action\": \"resetAlarm\"}","outTopic": "i/command/manager"},"waterLeak": {"inPattern": "{{ leak if json.waterLeak == true else dry  }}","inTopic": "i/status/manager"}},"cloud": false,"discovery": false,"exposes": ["waterLeak","switch"],"id": "manager_3","name": "Контроллер протечки","options": {"retain": true},"real": true},{"active": true,"bindings": {"running": {"inPattern": "{{ json.running }}","inTopic": "i/status/manager"},"targetTemperature": {"inPattern": "{{ json.targetTemperature }}","inTopic": "i/status/manager","outPattern": "{\"action\": \"setTargetTemperature\", \"value\": {{ value }}}","outTopic": "i/command/manager"},"temperature": {"inPattern": "{{ json.temperature }}","inTopic": "i/status/manager"}},"cloud": false,"discovery": false,"exposes": ["thermostat"],"id": "manager","name": "Термостат","options": {"retain": true,"runningStatus": true,"targetTemperature": {"icon": "mdi:target","max": 35,"min": 15,"name": "Целевая температура","step": 0.5,"unit": "°C"},"temperature": {"icon": "mdi:thermometer","name": "Текущая температура","precision": 2}},"real": true},{"active": true,"bindings": {"status": {"inPattern": "{{ on if json.relay == true else off }}","inTopic": "i/status/manager","outPattern": "{\"action\": \"setRelay\", \"enabled\": {{ true if value == 'on' else false }}}","outTopic": "i/command/manager"}},"cloud": false,"discovery": false,"exposes": ["switch"],"id": "manager_1","name": "Электричество","options": {"retain": true},"real": true}],"timestamp": 1760353253,"version": "2.1.2"}' > /opt/homed-custom/database.json

echo "$REF_CONFIG" | tee /etc/homed/homed-zigbee.conf >/dev/null

CONF_FILES="/etc/homed/homed-web.conf /etc/homed/homed-zigbee.conf /etc/homed/homed-automation.conf /etc/homed/homed-custom.conf /etc/homed/homed-modbus.conf"
for conf in $CONF_FILES; do
    if [ -f "$conf" ]; then
        sed 's/prefix=homed/prefix=i/g' "$conf" > "$conf.tmp" && mv "$conf.tmp" "$conf"
    fi
done

# Обновляем логотипы homed-web (если каталог существует)
if [ -d "/usr/share/homed-web/img" ]; 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
fi

# Изменяем title в index.html homed-web
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

# Изменяем username и password в homed-web.conf
if [ -f "/etc/homed/homed-web.conf" ]; then
    sed 's/^username=homed$/username=i/' /etc/homed/homed-web.conf > /etc/homed/homed-web.conf.tmp && mv /etc/homed/homed-web.conf.tmp /etc/homed/homed-web.conf
    sed 's/^password=homed$/password=Admin@WebI/' /etc/homed/homed-web.conf > /etc/homed/homed-web.conf.tmp && mv /etc/homed/homed-web.conf.tmp /etc/homed/homed-web.conf
fi

sed 's/port=\/dev\/ttyS1/port=\/dev\/ttyS2/g' /etc/homed/homed-modbus.conf > /etc/homed/homed-modbus.conf.tmp && mv /etc/homed/homed-modbus.conf.tmp /etc/homed/homed-modbus.conf

# Получаем токен
if [ -n "$TOKEN" ]; then
    echo "Используется токен из переменной окружения"
elif [ -n "$1" ]; then
    TOKEN="$1"
    echo "Используется токен из параметра"
else
    echo "Введи token:"
    read TOKEN
fi

# Создаем или обновляем конфигурационный файл i-cloud
if [ -f "/etc/i-cloud.conf" ]; then
    # Remove any existing token lines to avoid duplicates
    grep -v "^token=" "/etc/i-cloud.conf" > "/etc/i-cloud.conf.tmp" && mv "/etc/i-cloud.conf.tmp" "/etc/i-cloud.conf"
    # Add the new token line
    echo "token=$TOKEN" >> "/etc/i-cloud.conf"
else
    # Create new config file with token
    echo "token=$TOKEN" > "/etc/i-cloud.conf"
fi

echo "Токен успешно сохранен в /etc/i-cloud.conf"

echo "--------------------------------"
echo "Checking installed packages... / Проверка установленных пакетов..."
for pkg in $PACKAGES; do
    check_package "$pkg"
done

restart_services

echo "--------------------------------"
echo "Setting up auto-update system... / Настройка системы автообновления..."

# Настраиваем только триггер при подключении к интернету

# Настраиваем систему автообновления (только создание сервиса)
setup_auto_update

echo "--------------------------------"
echo "Generating unique MAC addresses... / Генерация уникальных MAC-адресов..."
echo "ВНИМАНИЕ: После изменения MAC-адреса eth0 SSH-соединение будет разорвано!"
echo "WARNING: SSH connection will be dropped after changing eth0 MAC address!"

generate_random_mac() {
    # Генерируем локально администрируемый MAC (второй символ из 2,6,a,e)
    printf "02:%02x:%02x:%02x:%02x:%02x" \
        $((RANDOM % 256)) \
        $((RANDOM % 256)) \
        $((RANDOM % 256)) \
        $((RANDOM % 256)) \
        $((RANDOM % 256))
}

# Генерируем MAC для WiFi интерфейсов (сначала WiFi, потом eth0)
WIFI_AP_MAC=$(generate_random_mac)
WIFI_STA_MAC=$(generate_random_mac)
echo "phy0-ap0 MAC: $WIFI_AP_MAC"
echo "phy0-sta0 MAC: $WIFI_STA_MAC"

# Устанавливаем MAC для phy0-sta0 напрямую
if [ -d "/sys/class/net/phy0-sta0" ]; then
    ip link set phy0-sta0 down
    ip link set phy0-sta0 address "$WIFI_STA_MAC"
    ip link set phy0-sta0 up
fi

# Устанавливаем MAC для phy0-ap0 напрямую (если существует)
if [ -d "/sys/class/net/phy0-ap0" ]; then
    ip link set phy0-ap0 down
    ip link set phy0-ap0 address "$WIFI_AP_MAC"
    ip link set phy0-ap0 up
fi

# Сохраняем в UCI конфиг для постоянства
if uci get wireless.default_radio0 >/dev/null 2>&1; then
    uci set wireless.default_radio0.macaddr="$WIFI_AP_MAC"
fi
if uci get wireless.@wifi-iface[0] >/dev/null 2>&1; then
    uci set wireless.@wifi-iface[0].macaddr="$WIFI_AP_MAC"
fi

if uci get wireless.sta >/dev/null 2>&1; then
    uci set wireless.sta.macaddr="$WIFI_STA_MAC"
fi
if uci get wireless.@wifi-iface[1] >/dev/null 2>&1; then
    uci set wireless.@wifi-iface[1].macaddr="$WIFI_STA_MAC"
fi

uci commit wireless

# Генерируем MAC для eth0 (в последнюю очередь, т.к. разрывает SSH)
ETH0_MAC=$(generate_random_mac)
echo "eth0 MAC: $ETH0_MAC"

# Сохраняем в UCI конфиг для постоянства
uci set network.lan.macaddr="$ETH0_MAC"
uci commit network

echo "All configuration completed successfully!"
echo "Все настройки завершены успешно!"
echo "Now changing eth0 MAC address - SSH will disconnect..."
sleep 2

# Устанавливаем MAC для eth0 напрямую (это разорвет SSH)
if [ -d "/sys/class/net/eth0" ]; then
    ip link set eth0 down
    ip link set eth0 address "$ETH0_MAC"
    ip link set eth0 up
fi

echo "--------------------------------"
