================================================================================
OPENWRT ARGON THEME MANAGER (manage_argon.sh) - LINUX EDITION USER MANUAL
Automated GitHub Download, Local Package Picker, Single-Pipe SSH Deployment,
Theme Removal with Reboot, and SSH Host Key Management for OpenWrt (apk)
================================================================================

Author:        Richard Lloyd (www.RichardLloydusa.com)
License:       MIT License
Script File:   manage_argon.sh
Default Target: root@192.168.1.1 (configurable via ROUTER_IP and ROUTER_USER)

--------------------------------------------------------------------------------
1. ARCHIVE CONTENTS & DIRECTORY STRUCTURE
--------------------------------------------------------------------------------
Extracting Linux_Argon_Theme_Install_OpenWrt.zip produces the following layout:

Linux_Argon_Theme_Install_OpenWrt/
|-- manage_argon.sh
|-- luci-theme-argon-3.1.2-r1.apk
|-- luci-theme-argon-3.1.3-r1.apk
|-- luci-theme-argon-3.2.0-r1.apk
|-- linux_user_manual_manage_argon_sh.txt
`-- OpenWrt Argon Theme Manager (Linux Edition) Manual.pdf

Keep manage_argon.sh and all luci-theme-argon*.apk files together in the same
directory so local folder scanning and GitHub downloads store packages in one
place.

--------------------------------------------------------------------------------
2. STARTUP BEHAVIOR & CONFIGURATION
--------------------------------------------------------------------------------
- Safety & Variables: Runs under #!/usr/bin/env bash with `set -u` enabled so
  unset variables are caught immediately.
- Defaults:
    ROUTER_IP="192.168.1.1"
    ROUTER_USER="root"
    GITHUB_API="https://api.github.com/repos/jerrykuku/luci-theme-argon/releases/latest"
- Directory Resolution: Resolves SCRIPT_DIR from BASH_SOURCE[0] and runs:
    cd "$SCRIPT_DIR"
  If changing directories fails, it prints an error, waits for Enter, and
  exits with status 1.
- Interactive Loop: Clears the screen on each iteration, prints the banner with
  target user/IP and SCRIPT_DIR, displays options [1] through [5], and loops
  until [5] is selected (invalid choices print an error and sleep 2 seconds).

--------------------------------------------------------------------------------
3. ADDING THEMES TO THE INSTALLATION DIRECTORY
--------------------------------------------------------------------------------
You can populate SCRIPT_DIR with Argon theme packages in two ways:

A. Manual Addition to the Folder
   1. Obtain a compatible OpenWrt .apk theme file.
   2. Ensure the filename matches `luci-theme-argon*.apk` (starts with
      `luci-theme-argon` and ends with `.apk`).
   3. Place the file inside the same directory as manage_argon.sh (alongside
      the pre-bundled 3.1.2-r1, 3.1.3-r1, and 3.2.0-r1 packages).
   4. Select Option [2] from the menu; manage_argon.sh dynamically rescans
      SCRIPT_DIR every time Option [2] runs without requiring code edits.

B. Automatic Download via Option [1]
   - Selecting Option [1] queries GitHub for the latest release asset matching
     `luci-theme-argon*.apk` and downloads it directly into
     `${SCRIPT_DIR}/${apk_file}`, keeping it in the directory for future
     local installs as well.

--------------------------------------------------------------------------------
4. COMPLETE FUNCTION & MENU REFERENCE
--------------------------------------------------------------------------------
[Helper] pause_return()
- Prints a blank line and waits for Enter (`read -r -p "Press Enter to return
  to the menu..."`) before returning to the main menu loop.

[Helper] show_ssh_hint()
- Prints:
  "If you see a REMOTE HOST IDENTIFICATION HAS CHANGED warning, return to the
   menu and select option [4] Clear SSH Host Key for ${ROUTER_IP} (Fix Changed
   Host Warning)."

[Helper] fetch_latest_release()
- Checks for `curl` (preferred: `curl -fsSL -H "User-Agent: OpenWrt-Argon-Manager"`)
  or `wget` (`wget -qO- --header="User-Agent: OpenWrt-Argon-Manager"`) to fetch
  the latest release JSON from GITHUB_API. Returns 1 if neither tool is
  installed or the request fails.
- Parses the JSON assets array for the first entry where `name` matches
  `luci-theme-argon*.apk` and `browser_download_url` is non-empty, outputting
  `<name>|<browser_download_url>` via `python3` (preferred) or `jq`. Returns 1
  if neither parser is available or no matching asset exists.

[Core Installer] run_install "<apk_file>"
- Streams the selected local file over a single SSH connection:
    tar -cf - "$apk_file" | ssh "${ROUTER_USER}@${ROUTER_IP}" \
      "tar -xf - -C /tmp && ls -la /tmp/luci-theme-argon*.apk && apk update &&
       apk add luci-compat && apk add --allow-untrusted
       /tmp/luci-theme-argon*.apk && /etc/init.d/uhttpd restart && reboot"
- Prompts for your router `root` password once per install.
- Captures `${PIPESTATUS[1]}` (the `ssh` exit code):
  * If non-zero: prints `"SSH install command failed (exit code $rc). Nothing
    was installed or rebooted."`, calls `show_ssh_hint`, and calls
    `pause_return` without claiming a reboot occurred.
  * If zero: prints `"Install command sent. Your router is rebooting to apply
    the Argon theme."` and calls `pause_return`.

[Option 1] download_and_install()
- Calls `fetch_latest_release`; on failure, prints connection/local-install
  guidance and calls `pause_return`.
- Splits the result into `apk_file` and `dl_url`, validating both are non-empty.
- Downloads into `${SCRIPT_DIR}/${apk_file}` using `curl -fL --progress-bar` or
  `wget -q --show-progress`.
- If the download command fails or `${SCRIPT_DIR}/${apk_file}` is missing or
  empty (`! -s`), removes any partial file with `rm -f`, prints `"Download
  failed."`, and returns to the menu.
- Otherwise calls `run_install "$apk_file"`.

[Option 2] local_install()
- Loops until a valid package is chosen or cancelled:
  * Preserves and restores the caller's `nullglob` shell option while scanning
    `"${SCRIPT_DIR}"/luci-theme-argon*.apk` for regular files (`-f`).
  * Prints `"Scanning \"$SCRIPT_DIR\" for luci-theme-argon*.apk... Found: $count"`.
  * If `count` is 0, prints instructions to add an `.apk` or use Option [1],
    pauses, and returns to the menu.
  * Lists each matching file as `[1]`, `[2]`, ... plus `[C] Cancel and return to
    menu`.
  * Entering `c` or `C` returns to the main menu; non-numeric or out-of-range
    entries print `"Invalid selection."`, pause, and re-prompt; a valid number
    calls `run_install "$chosen"`.

[Option 3] remove_argon()
- Connects over SSH once and runs:
    apk del --no-cache luci-theme-argon; rm -f /tmp/luci-theme-argon*.apk;
    uci -q delete luci.themes.Argon; uci commit luci;
    rm -rf /tmp/luci-indexcache /tmp/luci-modulecache/;
    rm -f /etc/config/argon; /etc/init.d/uhttpd restart && reboot
- If `ssh` returns non-zero, prints `"SSH cleanup command returned an error."`,
  calls `show_ssh_hint`, and returns to the menu.
- On success, prints `"Done. Argon theme removed and router is rebooting."` and
  calls `pause_return`.

[Option 4] clear_host_key()
- Runs `ssh-keygen -R "$ROUTER_IP"` to remove stale host keys from
  `~/.ssh/known_hosts`.
- Reports failure if `ssh-keygen` returns non-zero; otherwise confirms the
  host key is cleared and the next SSH connection will prompt to trust the
  new key once.

[Option 5] Exit
- Exits the script cleanly with status `0` (`exit 0`).

--------------------------------------------------------------------------------
5. PREREQUISITES & TROUBLESHOOTING
--------------------------------------------------------------------------------
- Make Executable First: Run `chmod +x manage_argon.sh` before `./manage_argon.sh`.
- Router & Network: Target OpenWrt router must use `apk`, have SSH enabled at
  ROUTER_IP (default `192.168.1.1`), and have internet access during installs
  for `apk update` and `apk add luci-compat`.
- Pre-Removal Step: Switch LuCI to the Bootstrap theme first (System > System >
  Language and Style > Design > Bootstrap > Save & Apply) before running [3].
- Changed Host Key Warning: If SSH reports `REMOTE HOST IDENTIFICATION HAS
  CHANGED`, the script fails safely without claiming a reboot and directs you
  to Option [4] (`Clear SSH Host Key for 192.168.1.1`).
================================================================================