#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

cmd_fix() {
  cd "$ROOT"
  npm install axios sharp fluent-ffmpeg @ffmpeg-installer/ffmpeg @ffprobe-installer/ffprobe
}

cmd_check() {
  node -e "require('axios'); require('sharp'); require('fluent-ffmpeg'); require('@ffmpeg-installer/ffmpeg'); require('@ffprobe-installer/ffprobe')"
}

cmd_test() {
  for file in "$ROOT"/tests/*.test.cjs; do
    node "$file"
  done
}

cmd_run() {
  local video=""
  local fps="5"
  local mode="full"
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --video) video="$2"; shift 2 ;;
      --fps) fps="$2"; shift 2 ;;
      --mode) mode="$2"; shift 2 ;;
      *) echo "Unknown option: $1"; exit 1 ;;
    esac
  done
  if [[ -z "$video" ]]; then
    echo "Usage: bash scripts/make.sh run --video FILE [--fps 5] [--mode full]"
    exit 1
  fi
  node -e "process.stdout.write(JSON.stringify({ videoUrl: process.argv[1], fps: Number(process.argv[2]), mode: process.argv[3] }))" "$video" "$fps" "$mode" | node "$ROOT/scripts/index.cjs"
}

case "${1:-}" in
  fix) cmd_fix ;;
  check) cmd_check ;;
  test) cmd_test ;;
  run) shift; cmd_run "$@" ;;
  *) echo "Usage: bash scripts/make.sh fix|check|test|run"; exit 1 ;;
esac
