#!/bin/bash

set -e

if [ "$EUID" -eq 0 ]; then
    echo "This script should not be run as root. Please run it as a normal user."
    exit 1
fi

if [ -z "$1" ]; then
    echo "Usage: $0 <new-hostname>"
    exit 1
fi

NEW_HOSTNAME="$1"

if ! sudo -v; then
    echo "Sudo access required. Exiting."
    exit 1
fi

if ! command -v brew &>/dev/null; then
    echo ""
    echo "Installing Homebrew..."
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    eval "$(/opt/homebrew/bin/brew shellenv 2>/dev/null || /usr/local/bin/brew shellenv)"
else
    echo "Homebrew already installed."
fi

echo ""
echo "Installing brew packages..."
/bin/bash ./scripts/macos-brew_restore.sh

echo ""
echo "Linking configs..."
python3 ./manage.py link macos --force

echo ""
echo "Changing hostname..."
/bin/bash ./scripts/macos-change_hostname.sh "$NEW_HOSTNAME"

echo ""
echo "Creating internal SSH keys..."
/bin/bash ./scripts/setup_ssh_keys.sh --comment "${USER}@${NEW_HOSTNAME}" --filename "internal"
/bin/bash ./scripts/setup_ssh_keys.sh --comment "${USER}@${NEW_HOSTNAME}" --filename "git"

echo ""
echo "Setup complete. Follow the next steps to finalize your environment:"

echo ""
echo "Set up UTM and configure DNS settings."

echo ""
echo "Once your VMs and DNS are set up, add your SSH key to the remote server:"
echo "   ssh-copy-id -i ~/.ssh/id_25519_internal $USER@<server-ip>"

echo ""
echo "Add your SSH key for Git access. Your public key is:"
echo "   $(cat ~/.ssh/id_ed25519_git.pub)"

echo ""
echo "Update your Git remote to use SSH instead of HTTPS:"
echo "   git remote set-url origin git@gitea.tomastm.com:tomas.mirchev/dotfiles.git"

echo ""
echo "Install WindowTagger. You can find the repository here:"
echo "   https://gitea.tomastm.com/tomas.mirchev/window-tagger"
