#!/bin/sh

# build_custom_openwrt_image.sh
# 2025-04-17
# by Gernot WALZL

# https://openwrt.org/docs/guide-user/additional-software/imagebuilder
# "make info" shows a list of available profiles.
# Unfortunately, luci (the web interface) is not part of the default packages.

VERSION=${VERSION:-"24.10.1"}
PROFILE=${PROFILE:-"openwrt_one"}
PACKAGES=${PACKAGES:-"luci-ssl ddns-scripts luci-app-ddns etherwake luci-app-wol kmod-usb-storage block-mount kmod-fs-ext4 samba4-server luci-app-samba4 openssh-sftp-server"}

set -e

get_target () {
  case "$1" in
   'openwrt_one')
    echo 'mediatek'
    ;;
   'linksys_wrt3200acm' | 'linksys_wrt1200ac')
    echo 'mvebu'
    ;;
   *)
    return 1
  esac
}

get_subtarget () {
  case "$1" in
   'openwrt_one')
    echo 'filogic'
    ;;
   'linksys_wrt3200acm' | 'linksys_wrt1200ac')
    echo 'cortexa9'
    ;;
   *)
    return 1
  esac
}

TARGET=$(get_target "$PROFILE")
SUBTARGET=$(get_subtarget "$PROFILE")
IMAGEBUILDER="openwrt-imagebuilder-${VERSION}-${TARGET}-${SUBTARGET}.Linux-x86_64.tar.zst"
DOWNLOAD="https://downloads.openwrt.org/releases/${VERSION}/targets/${TARGET}/${SUBTARGET}/${IMAGEBUILDER}"

if [ ! -f "$IMAGEBUILDER" ]; then
  wget -O "$IMAGEBUILDER" "$DOWNLOAD"
fi
tar xvf "$IMAGEBUILDER"
cd "openwrt-imagebuilder-${VERSION}-${TARGET}-${SUBTARGET}.Linux-x86_64"
make image PROFILE="$PROFILE" PACKAGES="$PACKAGES"
cat "bin/targets/${TARGET}/${SUBTARGET}/sha256sums"
find "bin/targets/${TARGET}/${SUBTARGET}/" -type f