#!/bin/bash

# ==========================================================================
# UID alignment script  (Linux  <->  macOS)
#
# Aligns a Linux user's UID/GID with macOS's default of 501 so that NFS
# (AUTH_SYS) permissions agree across machines. NFS trusts NUMERIC ids, and
# macOS starts users at 501 while most Linux distros start at 1000 — so the
# "same" person is two different numbers until you fix it.
#
# Sanitized public version — set TARGET_USER below before running.
# Companion to: https://www.jonathanbeard.io/blog/2026/06/06/cross-platform-home-storage-nfs-smb.html
#
# WARNING: destructive. It kills the target user's processes, renumbers the
#          account, and chowns their files. Back up / snapshot first.
#
#   sudo ./fix_uid.sh setup     # create a temp admin to work from
#   sudo ./fix_uid.sh migrate   # run while logged in as that temp admin
# ==========================================================================

TARGET_USER="youruser"          # <-- the account to renumber
NEW_UID=501
NEW_GID=501
TEMP_USER="tempadmin"
TEMP_PASS="$(openssl rand -base64 12)"   # random throwaway; printed once at setup

# Check for root
if [ "$EUID" -ne 0 ]; then
  echo "Please run as root: sudo ./fix_uid.sh [setup|migrate]"
  exit 1
fi

MODE=$1

# ==========================================================================
# MODE 1: SETUP — create a temporary admin you can log in as
# ==========================================================================
if [ "$MODE" == "setup" ]; then
    echo ">>> STEP 1: Creating temporary admin user..."

    if id "$TEMP_USER" &>/dev/null; then
        echo "User $TEMP_USER already exists."
    else
        useradd -m -G sudo -s /bin/bash "$TEMP_USER"
        echo "$TEMP_USER:$TEMP_PASS" | chpasswd
        echo "Created user '$TEMP_USER' with password: $TEMP_PASS"
        echo "(Write it down — it's a throwaway and gets deleted at the end.)"
    fi

    echo ""
    echo "!!! NEXT STEPS !!!"
    echo "1. Log out of your current session completely."
    echo "2. Switch to a TTY (text) terminal:  Ctrl+Alt+F3"
    echo "3. Log in as '$TEMP_USER'."
    echo "4. Run this script again:  sudo ./fix_uid.sh migrate"
    exit 0
fi

# ==========================================================================
# MODE 2: MIGRATE — renumber TARGET_USER to 501 (run as the temp admin)
# ==========================================================================
if [ "$MODE" == "migrate" ]; then

    # Safety: ensure we are NOT running as the user we're about to renumber.
    CURRENT_USER=$(logname 2>/dev/null || echo "$SUDO_USER")
    if [ "$CURRENT_USER" == "$TARGET_USER" ]; then
        echo "ERROR: You are still logged in as $TARGET_USER."
        echo "You MUST log out and log in as $TEMP_USER to run this."
        exit 1
    fi

    echo ">>> STEP 2: Migrating UID for $TARGET_USER..."

    OLD_UID=$(id -u "$TARGET_USER")
    echo "Current UID detected as: $OLD_UID"

    if [ "$OLD_UID" == "$NEW_UID" ]; then
        echo "UID is already $NEW_UID. Nothing to do!"
        exit 0
    fi

    # 1. Free the account
    echo "-> Killing active processes for $TARGET_USER..."
    pkill -u "$TARGET_USER"; sleep 2
    pkill -9 -u "$TARGET_USER" || true

    # 2. Renumber UID
    echo "-> Changing UID to $NEW_UID..."
    usermod -u "$NEW_UID" "$TARGET_USER"

    # 3. Renumber primary GID
    echo "-> Changing GID to $NEW_GID..."
    if getent group "$NEW_GID" >/dev/null; then
        echo "   Group $NEW_GID already exists; pointing user at it."
        usermod -g "$NEW_GID" "$TARGET_USER"
    else
        groupmod -g "$NEW_GID" "$TARGET_USER"
    fi

    # 4. Fix home directory ownership
    echo "-> Fixing permissions in /home/$TARGET_USER..."
    chown -R "$NEW_UID":"$NEW_GID" /home/"$TARGET_USER"

    # 5. Re-own stray files on the LOCAL root filesystem only.
    #    -xdev is load-bearing: it stops the scan from crossing into mounted
    #    filesystems (like your NFS pool), so you never rewrite server-side
    #    ownership by accident.
    echo "-> Scanning local root fs for files owned by old UID ($OLD_UID)..."
    find / -xdev -uid "$OLD_UID" -exec chown -h "$NEW_UID":"$NEW_GID" {} + 2>/dev/null || true

    echo "----------------------------------------------------"
    echo "SUCCESS! UID changed to $NEW_UID."
    echo "----------------------------------------------------"
    echo "1. Reboot:                 sudo reboot"
    echo "2. Log in as $TARGET_USER."
    echo "3. Verify your UID:        id"
    echo "4. Verify NFS access."
    echo "5. Remove the temp user:   sudo userdel -r $TEMP_USER"
    exit 0
fi

# Fallback
echo "Usage: sudo ./fix_uid.sh [setup|migrate]"
