#!/bin/bash
#
# Festival 1.96 with Nitech Voices - Automated Build Script
# This script compiles Festival 1.96 with Nitech HTS voices and creates a Debian package
#

set -e  # Exit on any error

# Function to print messages
print_status() {
    echo "==> $1"
}

print_success() {
    echo "✓ $1"
}

print_warning() {
    echo "! $1"
}

print_error() {
    echo "✗ $1"
}

# Check if running as root (we don't want that)
if [ "$EUID" -eq 0 ]; then 
    print_error "Please do not run this script as root or with sudo"
    print_status "The script will ask for sudo password when needed"
    exit 1
fi

# Create main working directory
WORK_DIR="festival196nitech"
print_status "Creating working directory: $WORK_DIR"
mkdir -p "$WORK_DIR"
cd "$WORK_DIR"
WORK_DIR=$(pwd)  # Get absolute path

print_success "Working directory created: $WORK_DIR"
echo ""

# Check dependencies
print_status "Checking dependencies..."
MISSING_DEPS=()

for cmd in gcc g++ make wget tar bzip2 gzip dpkg-deb; do
    if ! command -v $cmd &> /dev/null; then
        MISSING_DEPS+=($cmd)
    fi
done

if [ ${#MISSING_DEPS[@]} -ne 0 ]; then
    print_error "Missing dependencies: ${MISSING_DEPS[*]}"
    print_status "Install them with: sudo apt-get install build-essential wget tar bzip2 gzip dpkg-dev"
    exit 1
fi

# Check for required libraries
print_status "Checking for required development libraries..."
if ! dpkg -l | grep -q libncurses.*-dev; then
    print_warning "libncurses development libraries not found"
    print_status "Install with: sudo apt-get install libncurses5-dev libtinfo-dev"
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

print_success "Dependencies check completed"
echo ""

# Download Festival and Speech Tools
print_status "Downloading Festival 1.96 and Speech Tools..."

wget -c http://festvox.org/packed/festival/1.96/speech_tools-1.2.96-beta.tar.gz
wget -c http://festvox.org/packed/festival/1.96/festival-1.96-beta.tar.gz
wget -c http://festvox.org/packed/festival/1.96/festlex_CMU.tar.gz
wget -c http://festvox.org/packed/festival/1.96/festlex_POSLEX.tar.gz
wget -c http://festvox.org/packed/festival/1.96/festvox_kallpc16k.tar.gz

print_success "Festival components downloaded"
echo ""

# Download Nitech voices
print_status "Downloading Nitech HTS voices..."
wget -c http://erewhon.superkuh.com/nitech_voices_for_festival_196.tar.gz

print_success "Nitech voices downloaded"
echo ""

# Extract everything
print_status "Extracting Festival and Speech Tools..."
tar xzf speech_tools-1.2.96-beta.tar.gz
tar xzf festival-1.96-beta.tar.gz
tar xzf festlex_CMU.tar.gz
tar xzf festlex_POSLEX.tar.gz
tar xzf festvox_kallpc16k.tar.gz

print_success "Festival components extracted"
echo ""

print_status "Extracting Nitech voices..."
tar xzf nitech_voices_for_festival_196.tar.gz

# Extract individual voice archives
for f in festvox_nitech_us_*_arctic_hts-2.1.tar.bz2; do
    if [ -f "$f" ]; then
        tar xjf "$f"
    fi
done

print_success "Nitech voices extracted"
echo ""

# Modify Speech Tools GCC configuration
print_status "Configuring Speech Tools for modern GCC..."

cd speech_tools
cp config/compilers/gcc_defaults.mak config/compilers/gcc_defaults.mak.backup

# Add linker flags
sed -i 's/^DEBUG_LINKFLAGS = -g$/DEBUG_LINKFLAGS = -g -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
sed -i 's/^WARN_LINKFLAGS = -Wall$/WARN_LINKFLAGS = -Wall -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
sed -i 's/^VERBOSE_LINKFLAGS =$/VERBOSE_LINKFLAGS = -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
sed -i 's/^OPTIMISE_LINKFLAGS = -O\$(OPTIMISE)$/OPTIMISE_LINKFLAGS = -O$(OPTIMISE) -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
sed -i 's/^PROFILE_prof_LINKFLAGS = -p$/PROFILE_prof_LINKFLAGS = -p -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
sed -i 's/^PROFILE_gprof_LINKFLAGS = -pg$/PROFILE_gprof_LINKFLAGS = -pg -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
sed -i 's/^SHARED_LINKFLAGS = -fno-shared-data$/SHARED_LINKFLAGS = -fno-shared-data -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
sed -i 's/^STATIC_LINKFLAGS = -static$/STATIC_LINKFLAGS = -static -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak

print_success "Speech Tools configuration updated"
echo ""

# Compile Speech Tools
print_status "Compiling Speech Tools (this may take several minutes)..."
./configure
make CXXFLAGS="-O0 -g -Wall -fpermissive -std=c++98 -D_GLIBCXX_USE_CXX11_ABI=0 -DSUPPORT_EDITLINE" 2>&1 | tee ../speech_tools_build.log

if [ ! -f "bin/wagon" ]; then
    print_error "Speech Tools compilation failed! Check speech_tools_build.log"
    exit 1
fi

print_success "Speech Tools compiled successfully"
echo ""

cd "$WORK_DIR"

# Modify Festival GCC configuration
print_status "Configuring Festival for modern GCC..."

cd festival

# First run configure to generate config files
./configure

# Check if gcc_defaults.mak exists, if not use the speech_tools one
if [ -f "config/compilers/gcc_defaults.mak" ]; then
    cp config/compilers/gcc_defaults.mak config/compilers/gcc_defaults.mak.backup
    
    # Add linker flags
    sed -i 's/^DEBUG_LINKFLAGS = -g$/DEBUG_LINKFLAGS = -g -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
    sed -i 's/^WARN_LINKFLAGS = -Wall$/WARN_LINKFLAGS = -Wall -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
    sed -i 's/^VERBOSE_LINKFLAGS =$/VERBOSE_LINKFLAGS = -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
    sed -i 's/^OPTIMISE_LINKFLAGS = -O\$(OPTIMISE)$/OPTIMISE_LINKFLAGS = -O$(OPTIMISE) -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
    sed -i 's/^PROFILE_prof_LINKFLAGS = -p$/PROFILE_prof_LINKFLAGS = -p -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
    sed -i 's/^PROFILE_gprof_LINKFLAGS = -pg$/PROFILE_gprof_LINKFLAGS = -pg -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
    sed -i 's/^SHARED_LINKFLAGS = -fno-shared-data$/SHARED_LINKFLAGS = -fno-shared-data -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
    sed -i 's/^STATIC_LINKFLAGS = -static$/STATIC_LINKFLAGS = -static -Wl,--allow-multiple-definition/' config/compilers/gcc_defaults.mak
else
    print_warning "gcc_defaults.mak not found, Festival may use Speech Tools compiler settings"
fi

# Modify project.mak to set correct library path
if [ -f "config/project.mak" ]; then
    cp config/project.mak config/project.mak.backup
    
    # Comment out the old line and add the new one
    grep -q "^FTLIBDIR = /usr/local/share/festival" config/project.mak || {
        sed -i '/^FTLIBDIR = \$(FESTIVAL_HOME)\/lib$/s/^/#/' config/project.mak
        echo "FTLIBDIR = /usr/local/share/festival" >> config/project.mak
    }
    
    # Verify the change
    if grep -q "^FTLIBDIR = /usr/local/share/festival" config/project.mak; then
        print_success "FTLIBDIR set to /usr/local/share/festival"
    else
        print_error "Failed to set FTLIBDIR!"
        exit 1
    fi
else
    print_error "config/project.mak not found!"
    exit 1
fi

print_success "Festival configuration updated"
echo ""

# Compile Festival
print_status "Compiling Festival (this may take several minutes)..."
make CXXFLAGS="-O0 -g -Wall -fpermissive -std=c++98 -D_GLIBCXX_USE_CXX11_ABI=0" 2>&1 | tee ../festival_build.log

if [ ! -f "bin/festival" ]; then
    print_error "Festival compilation failed! Check festival_build.log"
    exit 1
fi

print_success "Festival compiled successfully"
echo ""

cd "$WORK_DIR"

# Test Festival from build directory
print_status "Testing Festival compilation..."
if echo "(quit)" | ./festival/bin/festival > /dev/null 2>&1; then
    print_success "Festival test passed"
else
    print_warning "Festival test had issues but continuing..."
fi
echo ""

# Create Debian package structure
print_status "Creating Debian package structure..."

DEB_DIR="festival-1.96-deb"
rm -rf "$DEB_DIR"

mkdir -p "$DEB_DIR/DEBIAN"
mkdir -p "$DEB_DIR/usr/local/bin"
mkdir -p "$DEB_DIR/usr/local/share/festival/voices/us"
mkdir -p "$DEB_DIR/usr/local/share/doc/festival"
mkdir -p "$DEB_DIR/etc/festival"

print_success "Package structure created"
echo ""

# Copy binaries
print_status "Copying Festival binaries..."
cp festival/bin/festival "$DEB_DIR/usr/local/bin/"
cp festival/bin/festival_client "$DEB_DIR/usr/local/bin/"
cp festival/bin/text2wave "$DEB_DIR/usr/local/bin/"

print_status "Copying Speech Tools utilities..."
cp speech_tools/bin/ch_wave "$DEB_DIR/usr/local/bin/"
cp speech_tools/bin/ch_track "$DEB_DIR/usr/local/bin/"
cp speech_tools/bin/wagon "$DEB_DIR/usr/local/bin/"

print_success "Binaries copied"
echo ""

# Copy Festival libraries
print_status "Copying Festival libraries and data..."
cp -r festival/lib/* "$DEB_DIR/usr/local/share/festival/"

print_success "Festival libraries copied"
echo ""

# Copy Nitech voices
print_status "Copying Nitech HTS voices..."
if [ -d "lib/voices/us" ]; then
    cp -r lib/voices/us/* "$DEB_DIR/usr/local/share/festival/voices/us/"
    cp lib/hts.scm "$DEB_DIR/usr/local/share/festival/"
    print_success "Nitech voices copied"
else
    print_error "Nitech voices not found in lib/voices/us/"
    exit 1
fi
echo ""

# Copy documentation
print_status "Copying documentation..."
cp festival/README "$DEB_DIR/usr/local/share/doc/festival/" 2>/dev/null || true
cp festival/ACKNOWLEDGMENTS "$DEB_DIR/usr/local/share/doc/festival/" 2>/dev/null || true
cp festival/COPYING "$DEB_DIR/usr/local/share/doc/festival/" 2>/dev/null || true

print_success "Documentation copied"
echo ""

# Create system-wide configuration
print_status "Creating system configuration..."
cat > "$DEB_DIR/usr/local/share/festival/siteinit.scm" << 'EOF'
;;; System-wide Festival configuration

; Use ALSA for audio output
(Parameter.set 'Audio_Method 'Audio_Command)
(Parameter.set 'Audio_Command "aplay -q -c 1 -t raw -f s16 -r $SR $FILE")

; Set default voice to SLT (high-quality female voice)
(set! voice_default 'voice_nitech_us_slt_arctic_hts)
EOF

# Also create in /etc/festival for reference
cat > "$DEB_DIR/etc/festival/siteinit.scm" << 'EOF'
;;; System-wide Festival configuration
;;; Note: The active configuration is in /usr/local/share/festival/siteinit.scm
;;; This file is for reference only.

; Use ALSA for audio output
(Parameter.set 'Audio_Method 'Audio_Command)
(Parameter.set 'Audio_Command "aplay -q -c 1 -t raw -f s16 -r $SR $FILE")

; Set default voice to SLT (high-quality female voice)
(set! voice_default 'voice_nitech_us_slt_arctic_hts)
EOF

print_success "System configuration created"
echo ""

# Create control file
print_status "Creating package control file..."

# Detect architecture
ARCH=$(dpkg --print-architecture)

cat > "$DEB_DIR/DEBIAN/control" << EOF
Package: festival
Version: 1.96-nitech1
Section: sound
Priority: optional
Architecture: $ARCH
Depends: libc6 (>= 2.31), libstdc++6 (>= 10), libncurses6, libtinfo6, alsa-utils
Maintainer: Festival Build Script <festival@localhost>
Description: Festival Speech Synthesis System with Nitech HTS Voices
 Festival is a general multi-lingual speech synthesis system developed
 at CSTR (Centre for Speech Technology Research). It offers a full text
 to speech system with various APIs, as well as an environment for
 development and research of speech synthesis techniques.
 .
 This is version 1.96 (July 2004) compiled for modern Linux systems
 with GCC compatibility patches.
 .
 This package includes:
  - Festival speech synthesis engine
  - Speech Tools utilities
  - CMU and POSLEX lexicons
  - Nitech HTS voices (high-quality parametric synthesis)
  - US English diphone voices
  - Pre-configured ALSA audio output
 .
 Available voices include:
  - nitech_us_slt_arctic_hts (female, high quality, default)
  - nitech_us_awb_arctic_hts (male)
  - nitech_us_bdl_arctic_hts (male)
  - nitech_us_clb_arctic_hts (female)
  - nitech_us_rms_arctic_hts (male)
  - nitech_us_jmk_arctic_hts (male)
EOF

print_success "Control file created"
echo ""

# Create post-install script
print_status "Creating post-install script..."
cat > "$DEB_DIR/DEBIAN/postinst" << 'EOF'
#!/bin/bash
set -e

# Ensure audsp binary is executable (critical for --tts mode)
find /usr/local/share/festival -type f -name "audsp" -exec chmod 755 {} \; 2>/dev/null || true

echo ""
echo "Festival 1.96 with Nitech HTS voices has been installed."
echo ""
echo "Quick tests:"
echo "  echo 'Hello world' | festival --tts"
echo "  echo \"Hello world\" | text2wave | aplay"
echo "  echo '(SayText \"Hello world\")' | festival"
echo ""
echo "Convert text to WAV file:"
echo "  echo \"Hello world\" | text2wave -o output.wav"
echo ""
echo "Interactive mode:"
echo "  festival"
echo "  festival> (SayText \"Hello world\")"
echo ""
echo "Default voice: nitech_us_slt_arctic_hts (female)"
echo "Configuration: /usr/local/share/festival/siteinit.scm"
echo ""

exit 0
EOF

chmod 755 "$DEB_DIR/DEBIAN/postinst"
print_success "Post-install script created"
echo ""

# Set correct permissions
print_status "Setting file permissions..."
sudo chown -R root:root "$DEB_DIR"
sudo chmod 755 "$DEB_DIR/usr/local/bin"/*

# Make sure all binaries in festival lib are executable
sudo find "$DEB_DIR/usr/local/share/festival" -type f -name "audsp" -exec chmod 755 {} \;
sudo find "$DEB_DIR/usr/local/share/festival/bin" -type f -exec chmod 755 {} \; 2>/dev/null || true

# Set directory and file permissions
sudo find "$DEB_DIR/usr/local/share/festival" -type d -exec chmod 755 {} \;
sudo find "$DEB_DIR/usr/local/share/festival" -type f -exec chmod 644 {} \;

# Re-apply executable permissions to binaries (in case the above made them non-executable)
sudo find "$DEB_DIR/usr/local/share/festival" -type f -name "audsp" -exec chmod 755 {} \;
sudo find "$DEB_DIR/usr/local/share/festival/bin" -type f -exec chmod 755 {} \; 2>/dev/null || true

print_success "Permissions set"
echo ""

# Build the package
print_status "Building Debian package..."
PACKAGE_NAME="festival_1.96-nitech1_${ARCH}.deb"
sudo dpkg-deb --build "$DEB_DIR"
sudo mv "${DEB_DIR}.deb" "$PACKAGE_NAME"
sudo chown $USER:$USER "$PACKAGE_NAME"

print_success "Debian package built: $PACKAGE_NAME"
echo ""

# Calculate package size
PACKAGE_SIZE=$(du -h "$PACKAGE_NAME" | cut -f1)

# Summary
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║            BUILD COMPLETED SUCCESSFULLY!                   ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
print_success "Package created: $PACKAGE_NAME"
print_success "Package size: $PACKAGE_SIZE"
print_success "Location: $WORK_DIR/$PACKAGE_NAME"
echo ""
echo "To install:"
echo "  sudo dpkg -i $PACKAGE_NAME"
echo ""
echo "To test after installation:"
echo "  echo 'Hello world' | festival --tts"
echo "  echo 'Hello world' | text2wave | aplay"
echo ""
echo "Build logs saved:"
echo "  - speech_tools_build.log"
echo "  - festival_build.log"
echo ""
print_status "All files are in: $WORK_DIR"
echo ""
