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

usage() {
  echo "Usage: $0 [--tag <image_tag>] [--output <tar_path>]" >&2
}

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
DEFAULT_OUTPUT="$PROJECT_ROOT/images/argus-master-dev.tar"
IMAGE_TAG="${IMAGE_TAG:-argus-master:latest}"
OUTPUT_PATH="$DEFAULT_OUTPUT"

while [[ "$#" -gt 0 ]]; do
  case "$1" in
    --tag)
      [[ $# -ge 2 ]] || { usage; exit 1; }
      IMAGE_TAG="$2"
      shift 2
      ;;
    --output)
      [[ $# -ge 2 ]] || { usage; exit 1; }
      OUTPUT_PATH="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      usage
      exit 1
      ;;
  esac
 done

mkdir -p "$(dirname "$OUTPUT_PATH")"
echo "[INFO] Saving image $IMAGE_TAG to $OUTPUT_PATH"
docker image save "$IMAGE_TAG" -o "$OUTPUT_PATH"
echo "[OK] Image saved"
