#!/usr/bin/env bash
source "$GIT_CONFIG/git.paths.conf"
set -euo pipefail

# ---------------------------------------------
# Git Installer System (Inline Version)
# External bundles only: docs.64, code.64, arch.64
# Base64 + gzip + checksum validation
# ---------------------------------------------

ROOT_DIR="$(pwd)/git"
CHUNK_DIR="$ROOT_DIR/data/chunks64"
DOC_DIR="$ROOT_DIR/docs"
CODE_DIR="$ROOT_DIR/code"
ARCH_DIR="$ROOT_DIR/arch"

mkdir -p "$CHUNK_DIR" "$DOC_DIR" "$CODE_DIR" "$ARCH_DIR"

# ---------------------------------------------
# Helper: decode a bundle
# ---------------------------------------------
decode_bundle() {
    local bundle_file="$1"
    local output_file="$2"

    echo "[*] Decoding: $bundle_file → $output_file"

    if [[ ! -f "$bundle_file" ]]; then
        echo "[ERROR] Bundle not found: $bundle_file"
        exit 1
    fi

base64 --decode < "$bundle_file" | gzip -d > "$output_file"

    local sum
    sum=$(sha256sum "$output_file" | awk '{print $1}')
    echo "[OK] SHA256: $sum"
}

# ---------------------------------------------
# Install Docs
# ---------------------------------------------
install_docs() {
    echo "[*] Installing docs..."
    decode_bundle "$CHUNK_DIR/docs.64" "$DOC_DIR/docs.txt"
    echo "[OK] Docs installed."
}

# ---------------------------------------------
# Install Code
# ---------------------------------------------
install_code() {
    echo "[*] Installing code..."
    decode_bundle "$CHUNK_DIR/code.64" "$CODE_DIR/code.txt"
    echo "[OK] Code installed."
}

# ---------------------------------------------
# Install Architecture
# ---------------------------------------------
install_arch() {
    echo "[*] Installing architecture..."
    decode_bundle "$CHUNK_DIR/arch.64" "$ARCH_DIR/arch.txt"
    echo "[OK] Architecture installed."
}

# ---------------------------------------------
# Simple Commit Prompt
# ---------------------------------------------
commit_prompt() {
    echo ""
    echo "---------------------------------------------"
    echo " Commit your installer changes?"
    echo "---------------------------------------------"
    read -rp "Enter commit message (or leave blank to skip): " msg

    if [[ -n "$msg" ]]; then
        git add "$ROOT_DIR"
        git commit -m "$msg"
        echo "[OK] Changes committed."
    else
        echo "[*] Commit skipped."
    fi
}

# ---------------------------------------------
# Main
# ---------------------------------------------
main() {
    echo "[*] Starting Git Installer System..."
    install_docs
    install_code
    install_arch
    commit_prompt
    echo "[DONE] Installer complete."
}

main

