# Execute this script with POSIX sh

# ==============================================================================
# BSD compatible installation tool
#
# SPDX-FileType: SOURCE
# SPDX-FileCopyrightText: Michael Bäuerle
# SPDX-License-Identifier: BSD-2-Clause
#
# Supported options (4.3BSD style):
#    -c       : Copy files instead of move
#    -s       : Strip installed binary file
#    -m mode  : Set permissions of installed file to <mode>
#    -o owner : Set owner of installed file to <owner>
#    -g group : Set group of installed file to <group>

set -e
set -u

STRIP=0
MOVE=1
MODE=""
OWNER=""
GROUP=""

while test -n "$1"
do
   case $1 in
   -c) MOVE=0
       shift
       continue
       ;;
   -s) STRIP=1
       shift
       continue
       ;;
   -m) shift
       MODE="$1"
       shift
       continue
       ;;
   -o) shift
       OWNER="$1"
       shift
       continue
       ;;
   -g) shift
       GROUP="$1"
       shift
       continue
       ;;
   *)  if test 2 -ne $#
       then
          printf "Error: Invalid parameters\n"
          exit 1
       fi
       break;
       ;;
   esac
done
SRC="$1"
TRG="$2"

# Install file
if test ! -f "$SRC"
then
   printf "Error: Source file \"%s\" does not exist\n" "$SRC"
   exit 1
fi
#printf "%s\n" "Installing file \"$SRC\" to \"$TRG\""
# Explicitly remove potentially existing target file first
# Required for Apple Silicon machines with signed binaries
rm -f "$TRG"
cat "$SRC" >"$TRG"
#printf "%s\n" "$TRG" >>$FILE_LIST
if test 0 -ne $MOVE
then
   rm -f "$SRC"
fi

# Strip installed file if requested
if test 0 -ne $STRIP
then
   strip "$TRG"
fi

# Set permissions of installed file if requested
if test -n "$MODE"
then
   chmod "$MODE" "$TRG"
fi

# Set owner of installed file
if test -n "$OWNER"
then
   printf "%s\n" "$0: Setting owner not implemented yet (ignored)"
fi

# Set group of installed file
if test -n "$GROUP"
then
   printf "%s\n" "$0: Setting group not implemented yet (ignored)"
fi
