#!/bin/bash

# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

set -e

help() {
    cat << EOF
Usage: $0 [--ta|--host|--plugin|--dir] <files...>

Options:
  --ta       Sync files to the TA (Trusted Application) directory inside the
             emulator. Use this for Trusted Application binaries (*.ta).

  --host     Sync files to the Host Application directory inside the emulator.
             Use this for client or host-side binaries.

  --plugin   Sync files to the Plugin directory inside the emulator. Use this
             for any plugin binaries or related files.

  --dir      Sync files directly to the root shared directory inside the emulator.
             Use this for syncing arbitrary files or directories not covered above.

Arguments:
  <files...> One or more files or directories to sync to the target directory.

Example:
  $0 --ta ta/target/release/myapp.ta
  $0 --host host/target/release/myhostapp

Environment:
  QEMU_HOST_SHARE_DIR must be set and point to the shared directory used by the
  emulator to access synced files.

EOF
}


# Validate required environment variables
: "${QEMU_HOST_SHARE_DIR:?QEMU_HOST_SHARE_DIR must be set}"

# Check arguments
[ $# -ge 2 ] || { help; exit 1; }

# Determine target directory
case "$1" in
    --ta)     TARGET="$QEMU_HOST_SHARE_DIR/ta" ;;
    --host)   TARGET="$QEMU_HOST_SHARE_DIR/host" ;;
    --plugin) TARGET="$QEMU_HOST_SHARE_DIR/plugin" ;;
    --dir)    TARGET="$QEMU_HOST_SHARE_DIR" ;;
    --help|-h) help; exit 0 ;;
    *) echo "Error: Invalid option '$1'. Use --help for usage."; exit 1 ;;
esac

shift
mkdir -p "$TARGET"

# Copy files
for item in "$@"; do
    cp -r "$item" "$TARGET/"
done

echo "✓ Synced to $TARGET for emulation use."