#!/bin/sh
# cr -- compile and run. Detects language from extension.
# Usage: cr file.c [args...]
#        cr file.cpp [args...]
#        cr file.go [args...]
#        cr file.rs [args...]
#        cr file.py [args...]

file="$1"; shift
[ -z "$file" ] && { echo "Usage: cr <file> [args...]"; exit 1; }
[ ! -f "$file" ] && { echo "File not found: $file"; exit 1; }

ext="${file##*.}"
base="${file%.*}"

case "$ext" in
    c)
        cc -std=c11 -Wall -Wextra -Wpedantic -g -O0 \
           -fsanitize=address,undefined "$file" -o "$base" -lm && "./$base" "$@"
        ;;
    cpp|cc|cxx)
        g++ -std=c++17 -O2 -Wall -Wextra "$file" -o "$base" && "./$base" "$@"
        ;;
    go)
        go run "$file" "$@"
        ;;
    rs)
        rustc "$file" -o "$base" && "./$base" "$@"
        ;;
    py)
        python3 "$file" "$@"
        ;;
    sh)
        sh "$file" "$@"
        ;;
    js)
        node "$file" "$@"
        ;;
    ts)
        npx tsx "$file" "$@"
        ;;
    *)
        echo "Unknown extension: .$ext"
        exit 1
        ;;
esac
