#!/system/bin/sh
# curl -sSL https://android-phone-resources.oss-cn-hangzhou.aliyuncs.com/script/install_openclaw.sh | sh
# export INSTALL_ONLY=true && curl -sSL https://android-phone-resources.oss-cn-hangzhou.aliyuncs.com/script/install_openclaw.sh | sh
# killall openclaw 2>/dev/null;/data/bin/openclaw gateway --port 18789 &

# Debug mode - set to true to skip download and installation if TARGET_DIR exists
DEBUG=${OC_DEBUG:-false}
INSTALL_ONLY=${INSTALL_ONLY:-false}
# OSS file path (can be overridden by first argument, e.g. termux/openclaw.tgz)
OSS_FILE_PATH="${1:-termux/openclaw.tgz}"

# Get region ID from system property
REGION_ID=$(getprop ro.boot.aliyun.region-id)

# Fallback public URL
FALLBACK_URL="https://android-phone-resources.oss-cn-hangzhou-internal.aliyuncs.com"

# Map region ID to internal OSS URL
get_region_url() {
    case "$1" in
        "cn-hangzhou")
            echo "https://android-phone-resources.oss-cn-hangzhou-internal.aliyuncs.com"
            ;;
        "cn-shenzhen")
            echo "https://acp-res-cn-shenzhen.oss-cn-shenzhen-internal.aliyuncs.com"
            ;;
        "cn-shanghai")
            echo "https://acp-res-cn-shanghai.oss-cn-shanghai-internal.aliyuncs.com"
            ;;
        "cn-beijing")
            echo "https://acp-res-cn-beijing.oss-cn-beijing-internal.aliyuncs.com"
            ;;
        "cn-guangzhou")
            echo "https://acp-res-cn-guangzhou.oss-cn-guangzhou-internal.aliyuncs.com"
            ;;
        "cn-hongkong")
            echo "https://acp-res-hk.oss-cn-hongkong-internal.aliyuncs.com"
            ;;
        "ap-southeast-1")
            echo "https://acp-res-sg.oss-ap-southeast-1-internal.aliyuncs.com"
            ;;
        *)
            echo ""
            ;;
    esac
}

# File paths
TEMP_DIR="/data/local/tmp"
TARGET_DIR="/data/vendor/openclaw"
BIN_PATH="/data/bin/openclaw"

# Download function with retry logic
download_file() {
    local url=$1
    local output=$2
    echo "Downloading..."

    # Use curl: -L follow redirects, -f fail on error, -S show errors, -s silent mode
    curl -L -f -S -s -o "$output" "$url"
    return $?
}

# Download with internal/public fallback
download_with_fallback() {
    local file_path=$1
    local output=$2

    # Try internal URL if region is detected
    if [ -n "$REGION_ID" ]; then
        INTERNAL_URL=$(get_region_url "$REGION_ID")

        if [ -n "$INTERNAL_URL" ]; then
            FULL_URL="${INTERNAL_URL}${file_path}"
            echo "Trying internal URL for openclaw.tgz"

            if download_file "$FULL_URL" "$output"; then
                echo "Internal download succeeded"
                return 0
            else
                echo "Internal download failed, trying public URL"
            fi
        else
            echo "No internal URL mapping for region $REGION_ID"
        fi
    else
        echo "Region ID not detected, using public URL"
    fi

    # Fallback to public URL
    FULL_URL="${FALLBACK_URL}${file_path}"
    echo "Downloading from public URL for openclaw.tgz"

    if download_file "$FULL_URL" "$output"; then
        echo "Public download succeeded"
        return 0
    else
        echo "Error: Download failed for openclaw.tgz"
        return 1
    fi
}

# Check DEBUG mode and skip installation if TARGET_DIR exists
killall openclaw > /dev/null 2>&1
stop openclaw > /dev/null 2>&1
if [ "$DEBUG" = "true" ] && [ -d "$TARGET_DIR" ]; then
    echo "DEBUG mode: TARGET_DIR exists, skipping download and installation"
    echo "Jumping to workspace setup..."
else
    curl -sSL https://android-phone-resources.oss-cn-hangzhou.aliyuncs.com/script/install_aiengine.sh | sh > /dev/null 2>&1
    rm /data/vendor/log/aiengine/* > /dev/null 2>&1

    # Main installation process
    echo "Starting openclaw installation..."

    # Download openclaw.tgz
    TGZ_FILE="${TEMP_DIR}/openclaw.tgz"
    if download_with_fallback "/$OSS_FILE_PATH" "$TGZ_FILE"; then
        echo "Download completed successfully"
    else
        echo "Error: Failed to download openclaw.tgz"
        exit 1
    fi

    # Create target directory
    echo "Creating target directory: $TARGET_DIR"
    rm -rf "$TARGET_DIR"
    mkdir -p "$TARGET_DIR/home"

    # Extract tgz file
    echo "Extracting openclaw.tgz to $TARGET_DIR"
    tar -xzf "$TGZ_FILE" -C "$TARGET_DIR"
    if [ $? -ne 0 ]; then
        echo "Error: Failed to extract openclaw.tgz"
        rm -f "$TGZ_FILE"
        exit 1
    fi
    sed -i 's|/tmp/openclaw|/data/vendor/openclaw/usr/tmp|g' /data/vendor/openclaw/lib/node_modules/openclaw/dist/logging/logger.js > /dev/null 2>&1
    sed -i 's|/tmp/openclaw|/data/vendor/openclaw/usr/tmp|g' /data/vendor/openclaw/lib/node_modules/openclaw/dist/entry.js > /dev/null 2>&1


    # Add execute permission to all files in the bin directory
    echo "Adding execute permissions to files in $TARGET_DIR/bin"
    chmod +x "$TARGET_DIR"/bin/* > /dev/null 2>&1

    # Create openclaw wrapper script in /data/bin
    echo "Creating openclaw wrapper at $BIN_PATH"
    mkdir -p "$(dirname $BIN_PATH)"

    cat > "$BIN_PATH" << 'EOF'
#!/system/bin/sh
PATH=$PATH:/data/vendor/openclaw/bin LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/system/lib64:/data/vendor/openclaw/lib PREFIX=/data/vendor/openclaw SHELL=/data/vendor/openclaw/bin/bash HOME=/data/vendor/openclaw/home TMPDIR=/data/vendor/openclaw/tmp TMP=/data/vendor/openclaw/tmp /data/vendor/openclaw/bin/node /data/vendor/openclaw/bin/openclaw "$@"
EOF
    chmod +x "$BIN_PATH"

    START_BIN="/data/bin/start-openclaw.sh"
    cat > "$START_BIN" << 'EOF'
#!/system/bin/sh
/data/bin/openclaw gateway --port 18789
EOF
    chmod +x "$START_BIN"

    CONFIG_BIN="/data/bin/config-openclaw.sh"
    cat > "$CONFIG_BIN" << 'EOF'
#!/system/bin/sh
if [ -z "$1" ]; then
    echo "Usage: $0 <api_key> [token] [model]"
    exit 1
fi
NEW_KEY="$1"
NEW_TOKEN="$2"
NEW_MODEL="$3"
if [ "$NEW_KEY" != "_" ]; then
case "$NEW_KEY" in
    sk-sp*)
        NEW_BASE_URL="https://coding.dashscope.aliyuncs.com/v1"
        ;;
    *)
        NEW_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"
        ;;
esac
sed -i 's/"apiKey": "[^"]*"/"apiKey": "'$NEW_KEY'"/' /data/vendor/openclaw/home/.openclaw/openclaw.json;
sed -i 's|"baseUrl": "[^"]*"|"baseUrl": "'$NEW_BASE_URL'"|' /data/vendor/openclaw/home/.openclaw/openclaw.json;
pm enable com.wuying.devinfo.openclaw > /dev/null 2>&1
fi
rm /data/vendor/openclaw/home/.openclaw/agents/main/agent/models.json > /dev/null 2>&1
if [ -n "$NEW_MODEL" ]; then
sed -i "s|\"primary\": \"[^\"]*\"|\"primary\": \"bailian/${NEW_MODEL}\"|" /data/vendor/openclaw/home/.openclaw/openclaw.json;
fi
if [ -n "$NEW_TOKEN" ] && [ "$NEW_TOKEN" != "_" ]; then
sed -i 's/"token": "[^"]*"/"token": "'$NEW_TOKEN'"/' /data/vendor/openclaw/home/.openclaw/openclaw.json;
sed -i "s|<string name=\"token\">[^<]*</string>|<string name=\"token\">${NEW_TOKEN}</string>|" /data/data/com.wuying.devinfo.openclaw/shared_prefs/config.xml;
fi
am force-stop com.wuying.devinfo.openclaw > /dev/null 2>&1
killall openclaw > /dev/null 2>&1
setprop ctl.restart openclaw > /dev/null 2>&1
EOF
    chmod +x "$CONFIG_BIN"


    INIT_RC="/data/etc/init/start_openclaw.rc"
    mkdir -p "$(dirname "${INIT_RC}")"
    cat > "${INIT_RC}" << 'EOF'
service openclaw /system/bin/logwrapper /data/bin/start-openclaw.sh
    class main
    user root
    group root
    seclabel u:r:su:s0

on property:sys.boot_completed=1
    start openclaw

EOF
    chmod 600 "${INIT_RC}"

    # Add execute permission to the wrapper script

    # Clean up
    echo "Cleaning up temporary files"
    rm -f "$TGZ_FILE"

    echo "openclaw installation completed successfully"

    if [ "$INSTALL_ONLY" = "false" ]; then
    # Prompt user for DashScope API Key
    # Check if running in a pipe (curl | sh), read from /dev/tty if available
    if [ -t 0 ]; then
        # Running interactively
        echo ""
        echo "Please enter your DashScope API Key (or press Enter to skip):"
        read -r DASHSCOPESK
    elif [ -c /dev/tty ]; then
        # Running in pipe, but /dev/tty is available
        echo ""
        echo "Please enter your DashScope API Key (or press Enter to skip):"
        read -r DASHSCOPESK </dev/tty
    else
        # No interactive input available, check environment variable
        DASHSCOPESK="${DASHSCOPESK:-}"
    fi
    fi

    # Use default placeholder if no key provided
    if [ -z "$DASHSCOPESK" ]; then
        DASHSCOPESK="DASHSCOPESK"
        echo "No API key provided, using placeholder. You can update it later in the config file."
        echo "Tip: You can set DASHSCOPESK environment variable before running this script."
    fi

    # Create openclaw config directory
    mkdir -p "/data/vendor/openclaw/home/.openclaw/workspace"
    cat > "/data/vendor/openclaw/home/.openclaw/openclaw.json" <<EOF
{
  "models": {
    "mode": "merge",
    "providers": {
      "bailian": {
        "baseUrl": "https://dashscope.aliyuncs.com/compatible-mode/v1",
        "apiKey": "$DASHSCOPESK",
        "api": "openai-completions",
        "models": [
          {
            "id": "qwen3.5-plus",
            "name": "qwen3.5-plus",
            "reasoning": false,
            "input": ["text", "image"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 1000000,
            "maxTokens": 65536
          },
          {
            "id": "qwen3-max-2026-01-23",
            "name": "qwen3-max-2026-01-23",
            "reasoning": false,
            "input": ["text"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 262144,
            "maxTokens": 65536
          },
          {
            "id": "qwen3-coder-next",
            "name": "qwen3-coder-next",
            "reasoning": false,
            "input": ["text"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 262144,
            "maxTokens": 65536
          },
          {
            "id": "qwen3-coder-plus",
            "name": "qwen3-coder-plus",
            "reasoning": false,
            "input": ["text"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 1000000,
            "maxTokens": 65536
          },
          {
            "id": "MiniMax-M2.5",
            "name": "MiniMax-M2.5",
            "reasoning": false,
            "input": ["text"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 204800,
            "maxTokens": 131072
          },
          {
            "id": "glm-5",
            "name": "glm-5",
            "reasoning": false,
            "input": ["text"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 202752,
            "maxTokens": 16384
          },
          {
            "id": "glm-4.7",
            "name": "glm-4.7",
            "reasoning": false,
            "input": ["text"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 202752,
            "maxTokens": 16384
          },
          {
            "id": "kimi-k2.5",
            "name": "kimi-k2.5",
            "reasoning": false,
            "input": ["text", "image"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 262144,
            "maxTokens": 32768
          }
        ]
      }
    }
  },
  "agents": {
    "defaults": {
      "model": {
        "primary": "bailian/qwen3.5-plus"
      },
      "workspace": "/data/vendor/openclaw/home/.openclaw/workspace"
    }
  },
  "gateway": {
    "port": 18789,
    "mode": "local",
    "bind": "lan",
    "auth": {
      "mode": "token",
      "token": "undefined"
    },
    "controlUi": {
      "allowInsecureAuth": true,
      "dangerouslyDisableDeviceAuth": true,
      "dangerouslyAllowHostHeaderOriginFallback": true
    },
    "tailscale": {
      "mode": "off",
      "resetOnExit": false
    }
  },
  "messages": {
    "ackReactionScope": "group-mentions"
  },
  "tools": {
    "profile": "full"
  }
}
EOF
    echo "Configuration file created at /data/vendor/openclaw/home/.openclaw/openclaw.json"
fi

# Start openclaw gateway in background and capture output
echo "Starting openclaw gateway..."
/data/bin/start-openclaw.sh > /data/vendor/openclaw/tmp/openclaw_gateway.log 2>&1 &
GATEWAY_PID=$!

# Create workspace and populate with templates
rm -rf /data/vendor/openclaw/home/.openclaw/agents/*
mkdir -p /data/vendor/openclaw/home/.openclaw/workspace
cp /data/vendor/openclaw/lib/node_modules/openclaw/docs/reference/templates/* /data/vendor/openclaw/home/.openclaw/workspace/
rm /data/vendor/openclaw/home/.openclaw/workspace/HEARTBEAT.md > /dev/null 2>&1
rm /data/vendor/openclaw/home/.openclaw/workspace/*.dev.md > /dev/null 2>&1
cat > /data/vendor/openclaw/tmp/system_config.tmp << "EOF"

## 🤖 System Configuration
- **This system is Android** with root access
- **Language Requirement: You MUST respond to all questions and interactions in Simplified Chinese (简体中文)**

### 🎯 Operation Priority (CRITICAL)
**Default: Use aiengine for ALL operations**

### Decision Flow
1. **Information queries & file operations** (查询系统信息、文件增删改查) → use `/system/bin/sh`
2. **ALL other operations** (UI interactions, app operations, system modifications) → use `/data/bin/aiengine`

### aiengine - Primary Automation Tool

**Usage:** `/data/bin/aiengine "<task description>"`

**Examples:**
```bash
/data/bin/aiengine "打开设置"
/data/bin/aiengine "点击登录按钮"
/data/bin/aiengine "开启暗黑模式"
/data/bin/aiengine "安装应用"
/data/bin/aiengine "修改系统设置"
```

**Rules:**
- Chinese commands → MUST use aiengine
- aiengine will output "Task completed." when task execution finishes - DO NOT call aiengine again unless user provides a new instruction need to use aiengine
- Wait for "Task completed." before next action
- When in doubt, use aiengine

### Shell Commands (Information Queries & File Operations)
Use for information queries and standard POSIX file operations with root privileges.

**Execution:**
- **Always execute through:** `/system/bin/sh -c "your command"`

**Network queries:**
- **Use `/system/bin/curl` for all network access and HTTP requests**

**Android-specific commands:**
- `pm` - package manager (list/query packages)
- `am` - activity manager (start activities, send intents)
- `dumpsys` - system service diagnostics
- `logcat` - view system logs
- `getprop` - read system properties

**Special tools:**
- `wya screencap -base64` - capture screenshots output with base64
- `wya input text -sys -append` - append text into text field
- `wya config -e locale <locale>` - change system locale (e.g., en-US, zh-CN)
- `wya config -e timezone <timezone>` - change system timezone (e.g., Asia/Shanghai)
- `setprop persist.location.data <latitude,longitude>` - set GPS location (e.g., 30.2482,120.1439)

EOF

cat /data/vendor/openclaw/home/.openclaw/workspace/TOOLS.md >> /data/vendor/openclaw/tmp/system_config.tmp 2>/dev/null
mv /data/vendor/openclaw/tmp/system_config.tmp /data/vendor/openclaw/home/.openclaw/workspace/TOOLS.md
if [ "$INSTALL_ONLY" = "true" ]; then
    pm disable com.wuying.devinfo.openclaw > /dev/null 2>&1
    NEW_TOKEN=undefined
    sed -i 's/"token": "[^"]*"/"token": "'$NEW_TOKEN'"/' /data/vendor/openclaw/home/.openclaw/openclaw.json > /dev/null 2>&1
    sed -i "s|<string name=\"token\">[^<]*</string>|<string name=\"token\">${NEW_TOKEN}</string>|" /data/data/com.wuying.devinfo.openclaw/shared_prefs/config.xml > /dev/null 2>&1
fi

# Wait for gateway to be ready by monitoring the log
echo "Waiting for gateway to start..."
TIMEOUT=200
ELAPSED=0
LOG_FILE="/data/vendor/openclaw/tmp/openclaw_gateway.log"
while [ $ELAPSED -lt $TIMEOUT ]; do
    # Use grep -F for literal string matching (no regex interpretation)
    if grep -F "started" "$LOG_FILE" > /dev/null 2>&1; then
        echo "Gateway is ready!"
        sleep 1
        break
    fi
    sleep 1
    ELAPSED=$((ELAPSED + 1))
done

# Check if gateway started successfully
if [ $ELAPSED -ge $TIMEOUT ]; then
    echo "Warning: Gateway did not start within ${TIMEOUT} seconds"
    echo "Check $LOG_FILE for details"
    echo "Gateway PID: $GATEWAY_PID"
else
    # Gateway is ready, open the browser
    echo "Opening browser..."

    # Create Via browser settings if not exists
    VIA_SETTINGS="/data/data/mark.via/shared_prefs/settings.xml"
    if [ ! -f "$VIA_SETTINGS" ]; then
        echo "Creating Via browser settings file..."
        mkdir -p "$(dirname "$VIA_SETTINGS")"
        cat > "$VIA_SETTINGS" << 'VIAEOF'
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <int name="changelogcode" value="20240801" />
    <int name="agreement2" value="1" />
</map>
VIAEOF
        chmod 666 "$VIA_SETTINGS"
        echo "Via browser settings created and permissions set to 666"
    fi

    if [ "$INSTALL_ONLY" = "true" ]; then
        killall openclaw > /dev/null 2>&1
        stop openclaw > /dev/null 2>&1
        rm -rf /data/vendor/log/* /data/vendor/aliyun /data/vendor/cloudmonitor
        echo "Installation completed."
        exit 0
    else
        am start -a android.intent.action.VIEW -d "http://127.0.0.1:18789/chat?session=main&token=undefined" -p mark.via
        echo "you can replace token with \"token-openclaw.sh <TOKEN>\" and run \"openclaw tui\" in terminal"
    fi
fi
