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

REMOTE_HOST="accone.aplikasi.web.id"
LOCAL_PATH="application/controllers/"
REMOTE_PATH="/home/one/project/accone/one-api/application/controllers/"

cd "$(dirname "$0")/.."

if ! command -v rsync >/dev/null 2>&1; then
  echo "rsync is required but was not found in PATH." >&2
  exit 1
fi

if ! command -v ssh >/dev/null 2>&1; then
  echo "ssh is required but was not found in PATH." >&2
  exit 1
fi

if ! command -v awk >/dev/null 2>&1; then
  echo "awk is required but was not found in PATH." >&2
  exit 1
fi

usage() {
  echo "Usage: $0 <test|sync> [remote_user]" >&2
  echo "Examples:" >&2
  echo "  $0 test" >&2
  echo "  $0 sync" >&2
  echo "  $0 test one" >&2
}

COMMAND="${1:-}"
REMOTE_USER="${2:-one}"
REMOTE="${REMOTE_USER}@${REMOTE_HOST}"

case "$COMMAND" in
  test)
    echo "Checking SSH connection to ${REMOTE}..."
    ssh -o ConnectTimeout=10 "$REMOTE" "test -d '$REMOTE_PATH'"

    echo
    echo "Files/folders that would be uploaded:"
    rsync -rzcin --out-format="%i %n%L" "$LOCAL_PATH" "${REMOTE}:${REMOTE_PATH}" \
      | awk '$1 ~ /^</ || $1 ~ /^cd/ { print }'
    ;;
  sync)
    rsync -rzcv "$LOCAL_PATH" "${REMOTE}:${REMOTE_PATH}"
    ;;
  *)
    usage
    exit 1
    ;;
esac
