#!/bin/sh
#
# cook-all - SliTaz cook: batch-cook packages from an ordered list.
# One package name per line, '#' and blank lines ignored. With no
# file argument, ./cookorder is tried first, then /etc/slitaz/cookorder.
#
# Usage:
#   cook-all                  # use ./cookorder, fallback /etc/slitaz/cookorder
#   cook-all <file>           # use the given list file
#   cook-all --resume         # skip packages that already have a taz/ dir
#   cook-all <file> --resume  # combine the two
#
# Copyright (C) SliTaz GNU/Linux - GNU GPL v3
#

. /usr/lib/slitaz/libcook.sh


usage() {
	cat <<EOT

$(boldify "$(_ 'Usage:')") cook-all [<file>] [--resume]

$(boldify "$(_ 'Commands:')")
  usage|help|--help|-h $(_ 'Display this short usage.')
  (no arg)             $(_ 'Cook from ./cookorder or /etc/slitaz/cookorder.')
  <file>               $(_ 'Cook packages listed in <file>, one per line.')

$(boldify "$(_ 'Options:')")
  --resume             $(_ 'Skip packages that already have a taz/ dir.')

$(boldify "$(_ 'Examples:')")
  cook-all                     $(_ 'cook everything from the default cookorder')
  cook-all my.list             $(_ 'cook from a custom list')
  cook-all --resume            $(_ 'restart a broken full rebuild')
  cook-all my.list --resume    $(_ 'same with a custom list')

$(boldify "$(_ 'About the list file:')")
  Plain text, one package name per line. Lines starting with '#' and
  blank lines are skipped. Search order when no file is given:
    1) ./cookorder
    2) /etc/slitaz/cookorder
  cook-all aborts if neither exists.

EOT
	exit 0
}


#
# Parse arguments
#

cookorder=''
resume=''

for arg in "$@"; do
	case "$arg" in
		usage|help|--help|-h) usage ;;
		--resume) resume='yes' ;;
		-*) _ 'Unknown option: %s' "$arg" >&2; usage ;;
		*) cookorder="$arg" ;;
	esac
done


#
# Resolve cookorder file
#

if [ -z "$cookorder" ]; then
	if [ -f ./cookorder ]; then
		cookorder='./cookorder'
	elif [ -f /etc/slitaz/cookorder ]; then
		cookorder='/etc/slitaz/cookorder'
	else
		die 'No cookorder found: pass a file or create /etc/slitaz/cookorder'
	fi
fi
[ -f "$cookorder" ] || die 'File not found: %s' "$cookorder"


#
# Cook
#

check_root
title 'Cooking all packages from %s' "$cookorder"
_ 'Starting cooking the list "%s"' "$cookorder" | log

count=0
fails=0
alllog="$LOGS/cook-all.log"
echo "$(date '+%F %R') cook-all start: $cookorder" >> "$alllog"

while IFS= read -r line; do
	case "$line" in
		''|\#*) continue ;;
		*) pkg="$line" ;;
	esac
	[ -n "$resume" ] && [ -d "$WOK/$pkg/taz" ] && continue
	if cook "$pkg"; then
		count=$(($count + 1))
		echo "$(date '+%F %R') OK $pkg" >> "$alllog"
	else
		fails=$(($fails + 1))
		broken
	fi
done < "$cookorder"

echo "$(date '+%F %R') done: $count built, $fails failed" >> "$alllog"
footer "$(_ '%s built, %s failed' "$count" "$fails")"
[ "$fails" -gt 0 ] && _ 'Failed packages logged in: %s' "$broken"
