#!/usr/bin/env bash

SETTINGS="settings.nix"
REPO_DIR=$(pwd)
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# 1. Generate settings.nix
if [ -f "$SETTINGS" ]; then
    echo -e "${YELLOW}settings.nix exists. overwrite? [y/N]${NC}"
    read -r confirm
    if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
        echo "keeping existing settings"
    else
        GENERATE=true
    fi
else
    GENERATE=true
fi

if [ "$GENERATE" = true ]; then
    username=$(whoami)
    userdesc=$(getent passwd "$username" | cut -d: -f5 | cut -d, -f1)
    userdesc=${userdesc:-$username}

    echo "user: $username ($userdesc)"
    echo ""

    echo "hostname:"
    read -r hostname

    echo "timezone [America/Edmonton]:"
    read -r tz
    tz=${tz:-America/Edmonton}

    echo "locale [en_CA.UTF-8]:"
    read -r locale
    locale=${locale:-en_CA.UTF-8}

    echo ""
    echo "{" > "$SETTINGS"
    echo "  hostname = \"$hostname\";" >> "$SETTINGS"
    echo "  username = \"$username\";" >> "$SETTINGS"
    echo "  userDescription = \"$userdesc\";" >> "$SETTINGS"
    echo "  timezone = \"$tz\";" >> "$SETTINGS"
    echo "  locale = \"$locale\";" >> "$SETTINGS"
    echo "  userGroups = [ \"networkmanager\" \"wheel\" \"docker\" \"plugdev\" ];" >> "$SETTINGS"
    echo "}" >> "$SETTINGS"
    echo "wrote $SETTINGS"
fi

# 2. Copy hardware-configuration.nix
if [ -f "/etc/nixos/hardware-configuration.nix" ]; then
    cp /etc/nixos/hardware-configuration.nix "$REPO_DIR/hardware-configuration.nix"
    echo "copied hardware-configuration.nix"
else
    echo -e "${YELLOW}no hardware-configuration.nix found - run nixos-generate-config first${NC}"
fi
