#!/usr/bin/env bash
# SPDX-License-Identifier: GPL-3.0-or-later
#
# A deliberately small `install(1)` compatibility wrapper for build trees on
# filesystems that map every created file to a shared owner and reject chmod.
# It is used only inside the private reviewed-core build. The final asset pack
# is hash-verified, and executable permission bits are irrelevant to browser
# JavaScript/WebAssembly files.

set -euo pipefail

directory_mode=false
create_leading=false
target_directory=
operands=()

while [[ $# -gt 0 ]]; do
  case "$1" in
    -d)
      directory_mode=true
      shift
      ;;
    -D)
      create_leading=true
      shift
      ;;
    -c | -p | -s | -v)
      shift
      ;;
    -m | -o | -g)
      if [[ $# -lt 2 ]]; then
        echo "install wrapper: $1 requires a value" >&2
        exit 2
      fi
      shift 2
      ;;
    -m* | -o* | -g*)
      shift
      ;;
    -t)
      if [[ $# -lt 2 ]]; then
        echo "install wrapper: -t requires a directory" >&2
        exit 2
      fi
      target_directory=$2
      shift 2
      ;;
    --)
      shift
      operands+=("$@")
      break
      ;;
    -*)
      echo "install wrapper: unsupported option $1" >&2
      exit 2
      ;;
    *)
      operands+=("$1")
      shift
      ;;
  esac
done

if $directory_mode; then
  if [[ ${#operands[@]} -eq 0 ]]; then
    echo "install wrapper: -d requires at least one directory" >&2
    exit 2
  fi
  mkdir -p -- "${operands[@]}"
  exit 0
fi

if [[ -n "$target_directory" ]]; then
  if [[ ${#operands[@]} -eq 0 ]]; then
    echo "install wrapper: -t requires at least one source" >&2
    exit 2
  fi
  mkdir -p -- "$target_directory"
  cp -f -- "${operands[@]}" "$target_directory/"
  exit 0
fi

if [[ ${#operands[@]} -lt 2 ]]; then
  echo "install wrapper: expected source and destination" >&2
  exit 2
fi

destination=${operands[-1]}
unset 'operands[-1]'
if $create_leading; then
  mkdir -p -- "$(dirname -- "$destination")"
fi

if [[ ${#operands[@]} -gt 1 || -d "$destination" ]]; then
  mkdir -p -- "$destination"
  cp -f -- "${operands[@]}" "$destination/"
else
  cp -f -- "${operands[0]}" "$destination"
fi
