#!/usr/bin/env bash

# nomarchy-sync: Automate backing up and restoring Nomarchy declarative configurations and dynamic state.

set -e

if [[ -z $1 ]]; then
    echo "Usage: nomarchy-sync <push|pull> [repo-url]"
    echo "  push: Backup current state to the configured repository."
    echo "  pull: Restore state from the configured repository and apply updates."
    exit 1
fi

COMMAND=$1
REPO_URL=$2

STATE_DIR="$HOME/.config/home-manager"
CONFIG_DIR="/etc/nixos"

# Identify the target repo directory (we use a local dot-folder to stage things)
SYNC_DIR="$HOME/.local/share/nomarchy-sync"

mkdir -p "$SYNC_DIR"
cd "$SYNC_DIR"

if [ ! -d ".git" ]; then
    if [[ -z $REPO_URL ]]; then
        echo "Error: No Git repository configured. Please provide a repo-url for the first run:"
        echo "Example: nomarchy-sync push git@github.com:username/nomarchy-backup.git"
        exit 1
    fi
    git init
    git remote add origin "$REPO_URL"
    # Basic configuration for automated commits
    git config user.name "Nomarchy Sync"
    git config user.email "sync@nomarchy.local"
fi

if [[ "$COMMAND" == "push" ]]; then
    echo "Synchronizing local configuration and state to backup repository..."
    
    # 1. Copy user flakes and nix files
    mkdir -p "$SYNC_DIR/nixos"
    cp -r "$CONFIG_DIR/flake.nix" "$CONFIG_DIR/system.nix" "$CONFIG_DIR/home.nix" "$SYNC_DIR/nixos/" 2>/dev/null || true
    
    # 2. Copy state files
    mkdir -p "$SYNC_DIR/state"
    cp -r "$STATE_DIR"/*.nix "$STATE_DIR"/*.json "$SYNC_DIR/state/" 2>/dev/null || true
    
    # 3. Commit and Push
    git add .
    if git diff-index --quiet HEAD --; then
        echo "No changes to backup."
    else
        git commit -m "Auto-sync backup from $(date +'%Y-%m-%d %H:%M:%S')"
        # We use a try-catch pattern for push because upstream might not exist yet
        echo "Pushing to remote..."
        git push -u origin master || git push -u origin main
        echo "Backup successful."
    fi

elif [[ "$COMMAND" == "pull" ]]; then
    echo "Pulling backup from remote repository..."
    git fetch
    # Hard reset to exactly match remote
    git reset --hard origin/master 2>/dev/null || git reset --hard origin/main
    
    echo "Restoring configuration and state..."
    
    # 1. Restore user flakes (Requires sudo)
    if [ -d "$SYNC_DIR/nixos" ]; then
        sudo cp -r "$SYNC_DIR/nixos/"* "$CONFIG_DIR/"
        sudo chmod -R u+w "$CONFIG_DIR"
    fi
    
    # 2. Restore state files
    if [ -d "$SYNC_DIR/state" ]; then
        mkdir -p "$STATE_DIR"
        cp -r "$SYNC_DIR/state/"* "$STATE_DIR/"
    fi
    
    echo "Applying updates..."
    # Apply the restored settings
    sudo nixos-rebuild switch --flake "$CONFIG_DIR#default"
    home-manager switch --flake "$CONFIG_DIR#default" --impure
    
    echo "Restore successful."

else
    echo "Unknown command: $COMMAND"
    exit 1
fi