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

usage() {
  cat <<'EOF'
Usage: sshupload.sh -l <local_glob> -r <remote_dir> -s <server> -u <user> -p <password>
EOF
}

local_glob=""
remote_dir=""
server=""
user=""
password=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    -l|--local) local_glob="$2"; shift 2;;
    -r|--remote) remote_dir="$2"; shift 2;;
    -s|--server) server="$2"; shift 2;;
    -u|--user) user="$2"; shift 2;;
    -p|--password) password="$2"; shift 2;;
    -h|--help) usage; exit 0;;
    *) echo "Unknown arg: $1" >&2; usage; exit 1;;
  esac
done

if [[ -z "$local_glob" || -z "$remote_dir" || -z "$server" || -z "$user" || -z "$password" ]]; then
  echo "Missing required params" >&2
  usage
  exit 1
fi

# Ensure sshpass installed
if ! command -v sshpass >/dev/null 2>&1; then
  if command -v brew >/dev/null 2>&1; then
    brew update
    brew install hudochenkov/sshpass/sshpass
  elif command -v apt-get >/dev/null 2>&1; then
    sudo apt-get update
    sudo apt-get install -y sshpass
  else
    echo "sshpass not found and no supported package manager" >&2
    exit 1
  fi
fi

user_host="${user}@${server}"

# Ensure remote dir exists and clear it
sshpass -p "$password" ssh -o StrictHostKeyChecking=no "$user_host" "mkdir -p '$remote_dir' && rm -f '$remote_dir'/*"

# Expand glob (supports ~ and patterns) and upload each file (compatible with macOS bash 3.x)
shopt -s nullglob
eval "files=( ${local_glob} )"
shopt -u nullglob

if [[ ${#files[@]} -eq 0 ]]; then
  echo "No files matched: $local_glob" >&2
  exit 1
fi

for f in "${files[@]}"; do
  sshpass -p "$password" scp -o StrictHostKeyChecking=no "$f" "$user_host:$remote_dir/"
done

echo "Upload completed"
