#!/bin/bash

# 定时任务配置：10 16 */5 * * /usr/bin/bash /home/hailey/shell/lede.sh >> /home/hailey/shell/lede.log 2>&1

set -euo pipefail

# ========= 配置部分 =========
LEDE_DIR="/home/hailey/lede"
LOG_FILE="/home/hailey/shell/lede.log"
BUILD_DIRS=("bin" "build_dir" "dl" "feeds" "staging_dir" "tmp")
JOBS=$(nproc)   # 自动检测 CPU 核心数

# ========= 工具函数 =========
log() {
  echo "[$(date '+%F %T')] $*" | tee -a "$LOG_FILE"
}

# ========= 清理函数 =========
clean_directories() {
  log "清理构建目录..."
  for dir in "${BUILD_DIRS[@]}"; do
    target="$LEDE_DIR/$dir"
    if [ -d "$target" ]; then
      log "删除目录: $target"
      rm -rf "$target"
    else
      log "目录不存在, 跳过: $target"
    fi
  done

  : > "$LOG_FILE"   # 清空日志文件
  make clean
  make dirclean
}

# ========= 更新代码和依赖 =========
update_feeds() {
  log "更新源码和 feeds..."
  cd "$LEDE_DIR" || exit 1
  git stash push -u || true
  git pull --rebase origin master
  git stash pop || true

  ./scripts/feeds update -a
  ./scripts/feeds install -a

  rm -rf feeds/packages/lang/golang
  git clone https://github.com/sbwml/packages_lang_golang -b 25.x feeds/packages/lang/golang
}

# ========= 编译函数 =========
build_project() {
  log "开始配置..."
  make defconfig

  log "下载依赖..."
  make download -j"$JOBS" || true
  make download V=s -j1   # 避免遗漏的包

  log "开始编译..."
  make V=s -j1
}

# ========= 主流程 =========
main() {
  pushd "$LEDE_DIR" > /dev/null

  start_time=$(date +%s)
  log "开始执行脚本..."

  case "${1:-}" in
    --clean)
      clean_directories
      ;;
    --update)
      update_feeds
      ;;
    --build)
      build_project
      ;;
    "" )
      clean_directories
      update_feeds
      build_project
      ;;
    *)
      echo "用法: $0 [--clean | --update | --build]"
      exit 1
      ;;
  esac

  end_time=$(date +%s)
  elapsed=$(( end_time - start_time ))

  hours=$(( elapsed / 3600 ))
  mins=$(( (elapsed % 3600) / 60 ))
  secs=$(( elapsed % 60 ))

  log "执行完成 ✅"
  log "总耗时: ${hours}小时 ${mins}分 ${secs}秒"

  popd > /dev/null
}

main "$@"
