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

SRC="/home/linux/"
DEST="/etc/skel/"

if [ "$(whoami)" != "root" ]; then
    echo "Must be root"
    exit 1
fi

if [ ! -d "$SRC" ]; then
    echo "Error: $SRC does not exist"
    exit 1
fi

echo "Setting permissions on source files..."
chmod +x "$SRC/.config/folderlangs.sh" 2>/dev/null || true
chmod +x "$SRC/.config/home-open.sh" 2>/dev/null || true
chmod +x "$SRC/Desktop/"* 2>/dev/null || true

echo "Copying $SRC to $DEST ..."
rsync -aHAX --delete --one-file-system \
  --exclude=".cache/" \
  --exclude=".gvfs/" \
  --exclude=".thumbnails/" \
  --exclude=".ssh/" \
  --exclude="/misc" \
  --exclude=".mozilla/" \
  --exclude=".config/google-chrome/" \
  --exclude=".config/chromium/" \
  --exclude=".config/libreoffice/" \
  --exclude=".local/share/Trash/" \
  --exclude=".local/share/recently-used.xbel" \
  --exclude=".local/share/.dryapt" \
  --exclude=".local/share/gvfs-metadata/" \
  --exclude=".local/share/containers/" \
  --exclude=".local/share/flatpak/" \
  --exclude=".local/share/baloo/" \
  --exclude=".bash_history" \
  --exclude=".xsession-errors" \
  --exclude=".xsession-errors.old" \
  --exclude="*.deb" \
  --exclude="*.swp" \
  --exclude="*.lock" \
  --exclude="*~" \
  --exclude="sudo-skelscript.sh" \
  "$SRC" "$DEST"

echo "Setting permissions on destination files..."
# Fix /etc/skel permissions — rsync copies home dir perms (700) which makes skel unreadable
# All directories must be 755, all files must be 644 (except executables)
chown -R root:root "$DEST"
find "$DEST" -type d -exec chmod 755 {} \;
find "$DEST" -type f -exec chmod 644 {} \;
chmod +x "$DEST/.config/folderlangs.sh" 2>/dev/null || true
chmod +x "$DEST/.config/home-open.sh" 2>/dev/null || true
chmod +x "$DEST/Desktop/"* 2>/dev/null || true

echo "Cleaning up root user files..."
rm -rf /root/.bash_history
rm -rf /root/.config/libreoffice
rm -rf /root/.local/share/recently-used.xbel
rm -rf /root/.ssh

echo "Done."
