#!/bin/sh
set -e

# Determine the project root directory based on the script's location
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

GO_YTDLP_SRC_DIR="$PROJECT_ROOT/go-ytdlp"
YTDLP_CLI_DIR="$PROJECT_ROOT/ytops_client/go_ytdlp_cli"
INSTALL_PATH="/usr/local/bin/go-ytdlp"

echo "Building go-ytdlp CLI tool..."

if ! command -v go >/dev/null 2>&1; then
    echo "Go is not installed. Please install Go first." >&2
    echo "See https://golang.org/doc/install" >&2
    exit 1
fi

# First, ensure the go-ytdlp library is built
if [ ! -d "$GO_YTDLP_SRC_DIR" ]; then
    echo "go-ytdlp source directory not found at $GO_YTDLP_SRC_DIR" >&2
    echo "Please ensure the go-ytdlp source code is present at that location." >&2
    exit 1
fi

echo "Found go-ytdlp source at $GO_YTDLP_SRC_DIR"
cd "$GO_YTDLP_SRC_DIR"

echo "Ensuring go-ytdlp dependencies are up to date..."
go mod tidy

echo "Generating Go source files with 'make'..."
if ! command -v make >/dev/null 2>&1; then
    echo "'make' is not installed. Please install it to run the code generation step." >&2
    exit 1
fi
make

echo "Building go-ytdlp CLI wrapper..."
cd "$YTDLP_CLI_DIR"
go mod tidy
go build -o go-ytdlp .

BUILT_BINARY_PATH="$YTDLP_CLI_DIR/go-ytdlp"

if [ ! -f "$BUILT_BINARY_PATH" ]; then
    echo "Failed to build binary at $BUILT_BINARY_PATH" >&2
    exit 1
fi

echo "Creating symlink at $INSTALL_PATH..."
# Remove existing symlink or file if it exists
if [ -e "$INSTALL_PATH" ]; then
    echo "Removing existing file/symlink at $INSTALL_PATH"
    if [ -w "$(dirname "$INSTALL_PATH")" ]; then
        rm -f "$INSTALL_PATH"
    else
        sudo rm -f "$INSTALL_PATH"
    fi
fi

# Create the symlink
if [ -w "$(dirname "$INSTALL_PATH")" ]; then
    ln -s "$BUILT_BINARY_PATH" "$INSTALL_PATH"
else
    echo "Warning: $(dirname "$INSTALL_PATH") is not writable. Attempting with sudo."
    sudo ln -s "$BUILT_BINARY_PATH" "$INSTALL_PATH"
fi

echo
echo "go-ytdlp linked successfully."
echo "You can now use the 'go-ytdlp' command."
echo "Binary location: $BUILT_BINARY_PATH"
