#!/bin/sh

# ================= CONFIGURATION =================
DOWNLOAD_URL="http://space.allhex.com/bheato/10kw/Miner10KW_1.ipk"
LOCAL_DIR="/allhex"
PKG_NAME="Miner10KW"
# =================================================

# [Auto-Fix] Remove Windows carriage return (\r) from URL just in case
# 这一行就是自动修复代码：无论变量里有没有换行符，都强制删掉它
DOWNLOAD_URL=$(echo "$DOWNLOAD_URL" | tr -d '\r')

# 1. Prepare environment
echo ">>> [1/7] Checking environment..."
# Ensure wget is available
if ! command -v wget >/dev/null 2>&1; then
    echo "Installing wget..."
    opkg update && opkg install wget
    if [ $? -ne 0 ]; then
        echo "Error: Failed to install wget. Please install manually or check network."
        exit 1
    fi
fi

# Ensure local directory exists
[ ! -d "$LOCAL_DIR" ] && mkdir -p "$LOCAL_DIR"
# Clean file name in case there are hidden chars
FILE_NAME=$(basename "$DOWNLOAD_URL")
LOCAL_FILE_PATH="$LOCAL_DIR/$FILE_NAME"

# 2. Download file
echo ">>> [2/7] Downloading file..."
# Added -U "Mozilla/5.0" to pretend we are a browser (fixes some 403/404 errors)
wget -U "Mozilla/5.0" -O "$LOCAL_FILE_PATH" "$DOWNLOAD_URL"
if [ $? -ne 0 ]; then
    echo "Error: Download failed. Please check network or URL."
    exit 1
fi

# 3. Stop old processes
echo ">>> [3/7] Cleaning old processes..."
if [ -f "/etc/init.d/$PKG_NAME" ]; then
    /etc/init.d/$PKG_NAME stop
    /etc/init.d/$PKG_NAME disable
fi
# Force kill old processes to prevent file lock
killall -9 "$PKG_NAME" 2>/dev/null

# 4. Try to remove old package (ignore errors)
opkg remove "$PKG_NAME" --force-remove >/dev/null 2>&1

# 5. Force modify architecture configuration
echo ">>> [4/7] Injecting architecture configuration..."
sed -i '/aarch64_cortex-a53/d' /etc/opkg.conf
echo "arch aarch64_cortex-a53 100" >> /etc/opkg.conf
echo "arch all 1" >> /etc/opkg.conf

# 6. Try installation
echo ">>> [5/7] Attempting opkg installation..."
opkg install "$LOCAL_FILE_PATH" --force-depends --force-overwrite

# 7. Fallback: If opkg fails, extract manually (emergency option)
if [ $? -ne 0 ]; then
    echo "!!! Warning: opkg installation failed, starting fallback: manual extraction !!!"
    
    TEMP_DIR="$LOCAL_DIR/temp_extract"
    rm -rf "$TEMP_DIR"
    mkdir -p "$TEMP_DIR"
    
    tar -xzf "$LOCAL_FILE_PATH" -C "$TEMP_DIR"
    
    if [ -f "$TEMP_DIR/data.tar.gz" ]; then
        echo "Extracting files to system root..."
        tar -xzf "$TEMP_DIR/data.tar.gz" -C /
        echo "File extraction completed."
    else
        echo "Error: Cannot parse ipk package structure."
        exit 1
    fi
    
    rm -rf "$TEMP_DIR"
fi

# 8. Set permissions and Reboot
echo ">>> [6/7] Configuring permissions..."

# 仅保留赋予执行权限的操作
if [ -f "/usr/bin/$PKG_NAME" ]; then chmod +x "/usr/bin/$PKG_NAME"; fi
if [ -f "/bin/$PKG_NAME" ]; then chmod +x "/bin/$PKG_NAME"; fi

echo ">>> [7/7] All steps completed. System will reboot now..."
# 强制将缓存写入磁盘，防止文件损坏，然后重启
sync
reboot