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

# Script Name: encode
# Description: Encoding/Decoding Swiss Army Knife for security testing
# Usage: encode base64 "hello"         # Base64 encode
#        encode base64d "aGVsbG8="     # Base64 decode
#        encode url "hello world"      # URL encode
#        encode urld "hello%20world"   # URL decode
#        encode html "<script>"        # HTML entity encode
#        encode htmld "&lt;script&gt;" # HTML entity decode
#        encode hex "hello"            # Hex encode
#        encode hexd "68656c6c6f"      # Hex decode
#        encode jwt <token>            # Decode JWT
#        encode hash md5 "password"    # Generate hash
#        pbpaste | encode base64       # Pipe from clipboard
#        encode xss "<script>"         # Multiple XSS encodings

VERSION="1.0.0"

# Colors
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly CYAN='\033[0;36m'
readonly BOLD='\033[1m'
readonly NC='\033[0m'

show_help() {
  echo -e "${BOLD}encode${NC} - Encoding/Decoding Swiss Army Knife v${VERSION}"
  echo
  echo -e "${BOLD}USAGE:${NC}"
  echo "  encode <operation> <input>"
  echo "  echo <input> | encode <operation>"
  echo
  echo -e "${BOLD}ENCODING OPERATIONS:${NC}"
  echo -e "  ${CYAN}base64${NC}       Base64 encode"
  echo -e "  ${CYAN}base64d${NC}      Base64 decode"
  echo -e "  ${CYAN}url${NC}          URL encode"
  echo -e "  ${CYAN}urld${NC}         URL decode"
  echo -e "  ${CYAN}html${NC}         HTML entity encode"
  echo -e "  ${CYAN}htmld${NC}        HTML entity decode"
  echo -e "  ${CYAN}hex${NC}          Hexadecimal encode"
  echo -e "  ${CYAN}hexd${NC}         Hexadecimal decode"
  echo -e "  ${CYAN}unicode${NC}      Unicode escape sequences (\\uXXXX)"
  echo -e "  ${CYAN}unicoded${NC}     Unicode unescape"
  echo
  echo -e "${BOLD}HASH OPERATIONS:${NC}"
  echo -e "  ${CYAN}hash md5${NC}     MD5 hash"
  echo -e "  ${CYAN}hash sha1${NC}    SHA1 hash"
  echo -e "  ${CYAN}hash sha256${NC}  SHA256 hash"
  echo -e "  ${CYAN}hash sha512${NC}  SHA512 hash"
  echo
  echo -e "${BOLD}SECURITY OPERATIONS:${NC}"
  echo -e "  ${CYAN}jwt${NC}          Decode JWT token (no verification)"
  echo -e "  ${CYAN}xss${NC}          Generate XSS payload variants"
  echo -e "  ${CYAN}sqli${NC}         Generate SQL injection variants"
  echo
  echo -e "${BOLD}EXAMPLES:${NC}"
  echo "  encode base64 \"hello world\""
  echo "  echo \"test\" | encode url"
  echo "  pbpaste | encode base64 | pbcopy"
  echo "  encode jwt eyJhbGc..."
  echo "  encode hash sha256 \"password\""
  echo "  encode xss \"<script>alert(1)</script>\""
  echo
  echo -e "${BOLD}SECURITY NOTE:${NC}"
  echo "  This tool is for authorized security testing and educational purposes only."
}

# Read input from argument or stdin
get_input() {
  if [[ $# -gt 0 ]]; then
    echo "$*"
  else
    cat
  fi
}

# Base64 operations
base64_encode() {
  local input=$(get_input "$@")
  echo -n "$input" | base64 -w 0 2>/dev/null || echo -n "$input" | base64
}

base64_decode() {
  local input=$(get_input "$@")
  echo -n "$input" | base64 -d 2>/dev/null || echo -n "$input" | base64 -D
}

# URL operations
url_encode() {
  local input=$(get_input "$@")
  python3 -c "import urllib.parse; print(urllib.parse.quote('$input'))"
}

url_decode() {
  local input=$(get_input "$@")
  python3 -c "import urllib.parse; print(urllib.parse.unquote('$input'))"
}

# HTML operations
html_encode() {
  local input=$(get_input "$@")
  python3 -c "import html; print(html.escape('$input'))"
}

html_decode() {
  local input=$(get_input "$@")
  python3 -c "import html; print(html.unescape('$input'))"
}

# Hex operations
hex_encode() {
  local input=$(get_input "$@")
  echo -n "$input" | xxd -p | tr -d '\n'
}

hex_decode() {
  local input=$(get_input "$@")
  echo -n "$input" | xxd -r -p
}

# Unicode operations
unicode_encode() {
  local input=$(get_input "$@")
  python3 << EOF
import sys
text = "$input"
result = ''.join(f'\\u{ord(c):04x}' for c in text)
print(result)
EOF
}

unicode_decode() {
  local input=$(get_input "$@")
  python3 -c "print('$input'.encode().decode('unicode_escape'))"
}

# JWT decode
jwt_decode() {
  local token=$(get_input "$@")

  # Split JWT into parts
  IFS='.' read -ra PARTS <<< "$token"

  if [[ ${#PARTS[@]} -ne 3 ]]; then
    echo "${RED}Error: Invalid JWT format${NC}" >&2
    return 1
  fi

  echo -e "${BOLD}${CYAN}=== JWT Header ===${NC}"
  echo "${PARTS[0]}" | base64_decode | python3 -m json.tool

  echo -e "\n${BOLD}${CYAN}=== JWT Payload ===${NC}"
  echo "${PARTS[1]}" | base64_decode | python3 -m json.tool

  echo -e "\n${BOLD}${YELLOW}Note: Signature not verified${NC}"
}

# Hash generation
generate_hash() {
  local algo=$1
  shift
  local input=$(get_input "$@")

  case "$algo" in
    md5)
      echo -n "$input" | md5sum | awk '{print $1}'
      ;;
    sha1)
      echo -n "$input" | sha1sum | awk '{print $1}'
      ;;
    sha256)
      echo -n "$input" | sha256sum | awk '{print $1}'
      ;;
    sha512)
      echo -n "$input" | sha512sum | awk '{print $1}'
      ;;
    *)
      echo "${RED}Error: Unknown hash algorithm: $algo${NC}" >&2
      echo "Available: md5, sha1, sha256, sha512" >&2
      return 1
      ;;
  esac
}

# XSS payload variants
xss_variants() {
  local input=$(get_input "$@")

  echo -e "${BOLD}${CYAN}=== XSS Payload Variants ===${NC}\n"

  echo -e "${YELLOW}[Original]${NC}"
  echo "$input"

  echo -e "\n${YELLOW}[URL Encoded]${NC}"
  url_encode "$input"

  echo -e "\n${YELLOW}[Double URL Encoded]${NC}"
  url_encode "$(url_encode "$input")"

  echo -e "\n${YELLOW}[HTML Entity Encoded]${NC}"
  html_encode "$input"

  echo -e "\n${YELLOW}[Hex Encoded]${NC}"
  hex_encode "$input"

  echo -e "\n${YELLOW}[Base64]${NC}"
  base64_encode "$input"

  echo -e "\n${YELLOW}[Unicode Escaped]${NC}"
  unicode_encode "$input"

  echo -e "\n${BOLD}${GREEN}Tip: Use these to bypass WAF filters${NC}"
}

# SQL injection variants
sqli_variants() {
  local input=$(get_input "$@")

  echo -e "${BOLD}${CYAN}=== SQL Injection Variants ===${NC}\n"

  echo -e "${YELLOW}[Original]${NC}"
  echo "$input"

  echo -e "\n${YELLOW}[URL Encoded]${NC}"
  url_encode "$input"

  echo -e "\n${YELLOW}[Double URL Encoded]${NC}"
  url_encode "$(url_encode "$input")"

  echo -e "\n${YELLOW}[Uppercase]${NC}"
  echo "$input" | tr '[:lower:]' '[:upper:]'

  echo -e "\n${YELLOW}[Mixed Case]${NC}"
  python3 << EOF
import random
text = "$input"
result = ''.join(c.upper() if random.random() > 0.5 else c.lower() for c in text)
print(result)
EOF

  echo -e "\n${YELLOW}[With Comments]${NC}"
  echo "$input" | sed 's/ /\/**\/ /g'

  echo -e "\n${BOLD}${GREEN}Tip: Combine with timing to test blind SQLi${NC}"
}

# Main logic
if [[ $# -eq 0 ]]; then
  show_help
  exit 0
fi

operation=$1
shift

case "$operation" in
  -h|--help|help)
    show_help
    ;;
  base64|b64)
    base64_encode "$@"
    ;;
  base64d|b64d)
    base64_decode "$@"
    ;;
  url)
    url_encode "$@"
    ;;
  urld)
    url_decode "$@"
    ;;
  html)
    html_encode "$@"
    ;;
  htmld)
    html_decode "$@"
    ;;
  hex)
    hex_encode "$@"
    ;;
  hexd)
    hex_decode "$@"
    ;;
  unicode|uni)
    unicode_encode "$@"
    ;;
  unicoded|unid)
    unicode_decode "$@"
    ;;
  jwt)
    jwt_decode "$@"
    ;;
  hash)
    if [[ $# -eq 0 ]]; then
      echo "${RED}Error: Hash algorithm required${NC}" >&2
      echo "Usage: encode hash <md5|sha1|sha256|sha512> <input>" >&2
      exit 1
    fi
    generate_hash "$@"
    ;;
  xss)
    xss_variants "$@"
    ;;
  sqli|sql)
    sqli_variants "$@"
    ;;
  *)
    echo "${RED}Error: Unknown operation: $operation${NC}" >&2
    echo "Run 'encode --help' for usage information" >&2
    exit 1
    ;;
esac
