#!/usr/bin/env bash
set -euo pipefail

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Update Doom Emacs to the latest commit from the doomemacs repository."
            echo ""
            echo "This script fetches the latest commit SHA from the default branch,"
            echo "updates the rev and sha256 in home/roles/emacs/default.nix, and"
            echo "prepares the configuration for a system rebuild."
            echo ""
            echo "Options:"
            echo "  --help, -h    Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
OWNER="doomemacs"
REPO="doomemacs"
FILE="home/roles/emacs/default.nix"
# Use current working directory as repo root (allows running from anywhere in the repo)
REPO_ROOT="${REPO_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
TARGET_FILE="$REPO_ROOT/$FILE"

echo -e "${GREEN}Updating DoomEmacs to latest commit...${NC}"

# Check if file exists
if [[ ! -f "$TARGET_FILE" ]]; then
    echo -e "${RED}Error: $TARGET_FILE not found${NC}"
    exit 1
fi

# Get the default branch first
echo "Fetching repository information..."
DEFAULT_BRANCH=$(curl -s "https://api.github.com/repos/$OWNER/$REPO" | jq -r '.default_branch')

if [[ -z "$DEFAULT_BRANCH" ]] || [[ "$DEFAULT_BRANCH" == "null" ]]; then
    echo -e "${RED}Error: Failed to fetch default branch${NC}"
    exit 1
fi

# Get the latest commit SHA from GitHub
echo "Fetching latest commit SHA from $DEFAULT_BRANCH branch..."
LATEST_SHA=$(curl -s "https://api.github.com/repos/$OWNER/$REPO/commits/$DEFAULT_BRANCH" | jq -r '.sha')

if [[ -z "$LATEST_SHA" ]] || [[ "$LATEST_SHA" == "null" ]]; then
    echo -e "${RED}Error: Failed to fetch latest commit SHA${NC}"
    exit 1
fi

echo -e "Latest commit: ${YELLOW}$LATEST_SHA${NC}"

# Get current SHA from file
CURRENT_SHA=$(grep -oP 'rev = "\K[^"]+' "$TARGET_FILE")
echo -e "Current commit: ${YELLOW}$CURRENT_SHA${NC}"

if [[ "$CURRENT_SHA" == "$LATEST_SHA" ]]; then
    echo -e "${GREEN}Already up to date!${NC}"
    exit 0
fi

# Update the rev field
echo "Updating rev in $FILE..."
sed -i "s/rev = \".*\"/rev = \"$LATEST_SHA\"/" "$TARGET_FILE"

# Fetch the new sha256 hash using nix-prefetch
echo "Fetching new sha256 hash..."
NEW_SHA256=$(nix-prefetch-url --unpack "https://github.com/$OWNER/$REPO/archive/$LATEST_SHA.tar.gz" 2>/dev/null)

if [[ -z "$NEW_SHA256" ]]; then
    echo -e "${RED}Error: Failed to fetch sha256 hash${NC}"
    # Revert the rev change
    sed -i "s/rev = \".*\"/rev = \"$CURRENT_SHA\"/" "$TARGET_FILE"
    exit 1
fi

# Convert to SRI hash format
SRI_HASH=$(nix hash to-sri --type sha256 "$NEW_SHA256")
echo -e "New sha256: ${YELLOW}$SRI_HASH${NC}"

# Update the sha256 field
sed -i "s|sha256 = \".*\"|sha256 = \"$SRI_HASH\"|" "$TARGET_FILE"

echo -e "${GREEN}Successfully updated DoomEmacs!${NC}"
echo -e "  Old commit: ${YELLOW}$CURRENT_SHA${NC}"
echo -e "  New commit: ${YELLOW}$LATEST_SHA${NC}"
echo -e "  New sha256: ${YELLOW}$SRI_HASH${NC}"
echo ""
echo "You can now rebuild your system with the updated DoomEmacs."
