#!/usr/bin/env bash
# VYCAT CLI v1.0.0
set -euo pipefail
BASE="https://vycat.org"
VERSION="1.0.0"
usage() {
  cat <<'HELP'
VYCAT CLI 1.0.0
Usage:
  vycat URL                 Shorten an HTTP(S) URL
  vycat f FILE              Upload a file
  vycat p IMAGE             Upload an image
  vycat t TEXT              Publish text (or: vycat t - for stdin)
  vycat c CODE              Publish code (or: vycat c - for stdin)
  vycat c --language LANG FILE   Publish code from a file
  vycat --help              Show help
  vycat --version           Show version
Install: https://vycat.org/cli/
All published content is publicly accessible. Never upload secrets.
HELP
}
fail() { printf 'vycat: %s\n' "$*" >&2; exit 1; }
command -v curl >/dev/null 2>&1 || fail "curl is required"
[[ $# -gt 0 ]] || { usage; exit 1; }
case "$1" in
  --help|-h) usage; exit 0 ;;
  --version|-v) printf '%s\n' "$VERSION"; exit 0 ;;
esac
mode="$1"; shift
case "$mode" in
  f|p)
    [[ $# -eq 1 ]] || fail "Expected exactly one file path"
    [[ -f "$1" && -r "$1" ]] || fail "File is missing or unreadable"
    endpoint="$mode/"
    response=$(curl --fail --silent --show-error --location --max-time 1800 --connect-timeout 15 --header 'Accept: text/plain' --form "file=@$1" "$BASE/$endpoint") || fail "Upload failed"
    ;;
  t|c)
    lang=clike
    if [[ "$mode" == c && "${1:-}" == "--language" ]]; then
      [[ $# -ge 3 ]] || fail "Expected language and file"
      lang="$2"; shift 2
      [[ "$lang" =~ ^[a-zA-Z0-9-]+$ ]] || fail "Invalid language"
    fi
    [[ $# -eq 1 ]] || fail "Expected text, file, or - (stdin)"
    endpoint="$mode/"
    [[ "$mode" == c ]] && endpoint="c/?language=$lang"
    if [[ "$1" == "-" ]]; then
      response=$(curl --fail --silent --show-error --max-time 120 --connect-timeout 15 -H 'Content-Type: application/octet-stream' --data-binary @- "$BASE/$endpoint") || fail "Publish failed"
    elif [[ "$mode" == c && -f "$1" ]]; then
      response=$(curl --fail --silent --show-error --max-time 120 --connect-timeout 15 -H 'Content-Type: application/octet-stream' --data-binary "@$1" "$BASE/$endpoint") || fail "Publish failed"
    else
      response=$(printf '%s' "$1" | curl --fail --silent --show-error --max-time 120 --connect-timeout 15 -H 'Content-Type: application/octet-stream' --data-binary @- "$BASE/$endpoint") || fail "Publish failed"
    fi
    ;;
  http://*|https://*)
    [[ $# -eq 0 ]] || fail "Expected a single URL"
    response=$(curl --fail --silent --show-error --max-time 60 --connect-timeout 15 -H 'Accept: text/plain' --data-urlencode "url=$mode" "$BASE/") || fail "Shortening failed"
    ;;
  *) fail "Unknown command. Run vycat --help" ;;
esac
response="${response%$'\n'}"
[[ "$response" =~ ^https://vycat\.org/(l|f|p|t|c)/[A-Za-z0-9]+/?$ ]] || fail "Unexpected server response: $response"
printf '%s\n' "$response"
