#!/bin/bash

# Path: scripts/provision.sh

set -e

GREEN='\033[1;32m'
YELLOW='\033[1;33m'
RED='\033[1;31m'
NC='\033[0m'

DEFAULT_USER="mangopig"
DEFAULT_UID="1000"
DEFAULT_GID="1000"
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "$SCRIPT_DIR/lib/distro.sh"

if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}Please run this script as root.${NC}"
  exit 1
fi

echo -e "${YELLOW}LOG: Detecting OS...${NC}"

echo -e "${YELLOW}LOG: Determining primary IPv4 address...${NC}"
if command -v hostname >/dev/null 2>&1 && hostname -I >/dev/null 2>&1; then
    IP=$(hostname -I | awk '{print $1}')
elif command -v ip >/dev/null 2>&1; then
    IP=$(ip route get 1.1.1.1 2>/dev/null | awk '/src/ {print $NF; exit}')
elif command -v ifconfig >/dev/null 2>&1; then
    IP=$(ifconfig | awk '/inet /{print $2}' | grep -v '^127' | head -n1)
else
    IP="127.0.0.1"
fi

echo -e "${YELLOW}LOG: Updating system and installing base tools...${NC}"

if is_arch_family; then
    pacman -Sy --noconfirm git make curl zsh sudo
    SUDO_GROUP="wheel"
elif is_debian_family; then
    apt-get update
    apt-get install -y git make curl sudo zsh
    SUDO_GROUP="sudo"
elif is_fedora_family; then
    if is_atomic_fedora; then
        echo -e "${RED}Provisioning on Fedora atomic systems is not supported by this root script.${NC}"
        echo -e "${RED}Use the normal user workflow and run make setup after login instead.${NC}"
        exit 1
    fi

    dnf install -y git make curl sudo zsh
    SUDO_GROUP="wheel"
else
    echo -e "${RED}Unsupported OS: $OS${NC}"
    exit 1
fi

ZSH_PATH="$(command -v zsh)"

if [ -t 0 ]; then
    echo -e "${GREEN}---------------------------------------${NC}"
    echo -e "${GREEN}      USER PROVISIONING WIZARD         ${NC}"
    echo -e "${GREEN}---------------------------------------${NC}"

    read -p "Enter Username (default: $DEFAULT_USER): " INPUT_USER
    USERNAME=${INPUT_USER:-$DEFAULT_USER}

    read -p "Enter UID (default: $DEFAULT_UID): " INPUT_UID
    USER_UID=${INPUT_UID:-$DEFAULT_UID}

    read -p "Enter GID (default: $DEFAULT_GID): " INPUT_GID
    USER_GID=${INPUT_GID:-$DEFAULT_GID}
else
    echo -e "${YELLOW}LOG: Non-interactive session detected. Using defaults.${NC}"
    USERNAME=${USERNAME:-$DEFAULT_USER}
    USER_UID=${USER_UID:-$DEFAULT_UID}
    USER_GID=${USER_GID:-$DEFAULT_GID}
fi

if getent group "$USER_GID" >/dev/null; then
    echo -e "${YELLOW}LOG: Group with GID $USER_GID already exists. Using it.${NC}"
else
    echo -e "${YELLOW}LOG: Creating group $USERNAME with GID $USER_GID...${NC}"
    groupadd -g "$USER_GID" "$USERNAME"
fi

if id "$USERNAME" &>/dev/null; then
    echo -e "${YELLOW}LOG: User $USERNAME already exists. Skipping creation.${NC}"
else
    echo -e "${YELLOW}LOG: Creating user $USERNAME...${NC}"
    useradd -m -u "$USER_UID" -g "$USER_GID" -G "$SUDO_GROUP" -s "$ZSH_PATH" "$USERNAME"
    echo -e "${GREEN}LOG: Setting password for $USERNAME...${NC}"
    
    if [ -t 0 ]; then
        echo -e "${GREEN}LOG: Setting password for $USERNAME...${NC}"
        passwd "$USERNAME"
    else
        echo -e "${YELLOW}LOG: Non-interactive: Setting password to '$USERNAME'...${NC}"
        echo "$USERNAME:$USERNAME" | chpasswd
    fi
fi

echo -e "${YELLOW}LOG: Configuring passwordless sudo...${NC}"
echo "$USERNAME ALL=(ALL) NOPASSWD:ALL" > "/etc/sudoers.d/90-$USERNAME"
chmod 0440 "/etc/sudoers.d/90-$USERNAME"

if is_arch_family || is_fedora_family; then
    sed -i 's/^# %wheel ALL=(ALL:ALL) ALL/%wheel ALL=(ALL:ALL) ALL/' /etc/sudoers
fi

echo -e "${YELLOW}LOG: Cloning dotfiles for $USERNAME...${NC}"
sudo -u "$USERNAME" git clone https://git.mangopig.tech/MangoPig/Dot-Zsh.git "/home/$USERNAME/Config/Dot-Zsh"


echo -e "${GREEN}✅ Server Provisioned!"
echo -e "${GREEN}   sudo su - $USERNAME${NC} OR logout and SSH back in as $USERNAME@$IP.${NC}"
echo -e "${GREEN}   Then run cd ~/Config/Dot-Zsh && make setup ${NC}"
