#!/bin/bash
set -euo pipefail

print_help() {
cat <<EOF
Usage: $0 --user USERNAME --uid NEW_UID [--gid NEW_GID] [--path DIR] [--dry-run]

Options:
  --user USERNAME     Target username (required)
  --uid NEW_UID       New UID to assign (required)
  --gid NEW_GID       New GID to assign (optional, default: same as UID)
  --path DIR          Optional root directory to restrict file ownership updates (default: '/')
  --dry-run           Show changes without applying them
  --help              Show this help message

Example:
  sudo $0 --user john --uid 1050           # changes UID and GID to 1050
  sudo $0 --user john --uid 1050 --gid 42  # changes UID to 1050 and GID to 42
  sudo $0 --user john --uid 1050 --dry-run
EOF
}

# Default values
PATH_RESTRICT="/"
DRY_RUN=false
GID_PROVIDED=false

# -------- Parse Args --------
while [[ $# -gt 0 ]]; do
    case "$1" in
        --user)
            USERNAME="$2"
            shift 2
            ;;
        --uid)
            NEW_UID="$2"
            shift 2
            ;;
        --gid)
            NEW_GID="$2"
            GID_PROVIDED=true
            shift 2
            ;;
        --path)
            PATH_RESTRICT="$2"
            shift 2
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --help)
            print_help
            exit 0
            ;;
        *)
            echo "❌ Unknown option: $1"
            print_help
            exit 1
            ;;
    esac
done

# -------- Validation --------
if [[ -z "${USERNAME:-}" || -z "${NEW_UID:-}" ]]; then
    echo "❌ Missing required parameters."
    print_help
    exit 1
fi

if ! id "$USERNAME" &>/dev/null; then
    echo "❌ User '$USERNAME' does not exist."
    exit 2
fi

if ! $GID_PROVIDED; then
    NEW_GID="$NEW_UID"
fi

OLD_UID=$(id -u "$USERNAME")
OLD_GID=$(id -g "$USERNAME")

echo "🔄 Changing UID:GID for '$USERNAME' from $OLD_UID:$OLD_GID to $NEW_UID:$NEW_GID"
echo "📁 Restricting file ownership updates to: $PATH_RESTRICT"
$DRY_RUN && echo "🧪 Running in DRY-RUN mode — no changes will be applied"

# -------- Ensure User is Logged Out --------
if pgrep -u "$USERNAME" > /dev/null; then
    echo "⚠️ User '$USERNAME' is currently logged in. Please log them out first."
    exit 3
fi

# -------- Apply Changes --------
if ! $DRY_RUN; then
    groupmod -g "$NEW_GID" "$USERNAME"
    usermod -u "$NEW_UID" -g "$NEW_GID" "$USERNAME"
fi

# -------- Update Ownership --------
echo "🔍 Scanning files for ownership fix..."

if $DRY_RUN; then
    find "$PATH_RESTRICT" -xdev -user "$OLD_UID" -exec echo chown -h "$NEW_UID" {} \;
    find "$PATH_RESTRICT" -xdev -group "$OLD_GID" -exec echo chgrp -h "$NEW_GID" {} \;
else
    find "$PATH_RESTRICT" -xdev -user "$OLD_UID" -exec chown -h "$NEW_UID" {} \;
    find "$PATH_RESTRICT" -xdev -group "$OLD_GID" -exec chgrp -h "$NEW_GID" {} \;
    echo "✅ UID and GID updated successfully for user '$USERNAME'."
fi