#!/usr/bin/env bash

set -e

TARGET_DIR="$HOME/Development/lavitz"
NIXOS_DIR="/etc/nixos"
CURRENT_DIR=$(pwd)
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}NixOS Configuration Setup${NC}"
echo ""

if [ "$CURRENT_DIR" != "$TARGET_DIR" ]; then
    echo -e "${YELLOW}Repository is not in $TARGET_DIR${NC}"

    if [ -d "$TARGET_DIR" ]; then
        echo -e "${RED}$TARGET_DIR already exists!${NC}"
        echo "Please remove it or move this repo manually."
        exit 1
    fi

    echo "Creating ~/Development directory..."
    mkdir -p "$HOME/Development"

    echo "Moving repository to $TARGET_DIR..."
    mv "$CURRENT_DIR" "$TARGET_DIR"

    echo -e "${GREEN}Repository moved to $TARGET_DIR${NC}"
    echo ""
    echo -e "${YELLOW}Please cd to $TARGET_DIR and run 'make init' again${NC}"
    exit 0
fi

echo -e "${GREEN}Repository is in correct location: $TARGET_DIR${NC}"
echo ""

if [ -f "/etc/nixos/hardware-configuration.nix" ]; then
    cp /etc/nixos/hardware-configuration.nix "$TARGET_DIR/hardware-configuration.nix"
    echo -e "${GREEN}Copied hardware-configuration.nix${NC}"
else
    echo -e "${YELLOW}No hardware-configuration.nix found${NC}"
    echo "Run 'sudo nixos-generate-config' first if this is a fresh install"
fi

if [ -L "$NIXOS_DIR" ]; then
    echo -e "${YELLOW}/etc/nixos is already a symlink${NC}"
    sudo rm "$NIXOS_DIR"
elif [ -d "$NIXOS_DIR" ]; then
    echo -e "${YELLOW}Backing up existing /etc/nixos to /etc/nixos.bak${NC}"
    sudo mv "$NIXOS_DIR" "${NIXOS_DIR}.bak"
fi

echo "Creating symlink: $TARGET_DIR -> $NIXOS_DIR"
sudo ln -sf "$TARGET_DIR" "$NIXOS_DIR"

echo ""
echo -e "${GREEN}Setup complete!${NC}"
echo ""
echo "Next steps:"
echo "  1. Ensure hardware-configuration.nix exists in $TARGET_DIR"
echo "  2. Run 'git add .' to track files (required for flakes)"
echo "  3. Run 'sudo nixos-rebuild switch --flake .#lavitz'"
