#!/bin/bash
set -e

# Build Debian package script

VERSION="1.0.0"
PACKAGE_NAME="adastra-storage"
BUILD_DIR="$(pwd)"
PACKAGE_DIR="$BUILD_DIR/packaging"
DEB_DIR="$BUILD_DIR/deb-build"
ARCH="amd64"

echo "Building Debian package for $PACKAGE_NAME version $VERSION"

# Clean previous build
rm -rf "$DEB_DIR"

# Create package structure
mkdir -p "$DEB_DIR/$PACKAGE_NAME/DEBIAN"
mkdir -p "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/bin"
mkdir -p "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/templates"
mkdir -p "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/migrations"
mkdir -p "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/data"
mkdir -p "$DEB_DIR/$PACKAGE_NAME/etc/systemd/system"

# Copy control files
cp "$PACKAGE_DIR/DEBIAN/control" "$DEB_DIR/$PACKAGE_NAME/DEBIAN/"
cp "$PACKAGE_DIR/DEBIAN/postinst" "$DEB_DIR/$PACKAGE_NAME/DEBIAN/"
cp "$PACKAGE_DIR/DEBIAN/prerm" "$DEB_DIR/$PACKAGE_NAME/DEBIAN/"
cp "$PACKAGE_DIR/DEBIAN/postrm" "$DEB_DIR/$PACKAGE_NAME/DEBIAN/"
chmod +x "$DEB_DIR/$PACKAGE_NAME/DEBIAN/postinst"
chmod +x "$DEB_DIR/$PACKAGE_NAME/DEBIAN/prerm"
chmod +x "$DEB_DIR/$PACKAGE_NAME/DEBIAN/postrm"

# Build the application
echo "Building application binary..."
cd "$BUILD_DIR"
go build -o "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/bin/adastra-storage" ./cmd/appliance

# Copy application files
echo "Copying application files..."
cp -r "$BUILD_DIR/internal/templates"/* "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/templates/"
cp -r "$BUILD_DIR/migrations"/* "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/migrations/"
cp "$PACKAGE_DIR/uninstall.sh" "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/uninstall.sh"
chmod +x "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/uninstall.sh"

# Copy systemd service
cp "$PACKAGE_DIR/adastra-storage.service" "$DEB_DIR/$PACKAGE_NAME/etc/systemd/system/"

# Set permissions
chmod 755 "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/bin/adastra-storage"
chmod 755 "$DEB_DIR/$PACKAGE_NAME/opt/adastra-storage/data"

# Build the package
echo "Building .deb package..."
cd "$DEB_DIR"
dpkg-deb --build "$PACKAGE_NAME" "${PACKAGE_NAME}_${VERSION}_${ARCH}.deb"

# Move to build directory
mv "${PACKAGE_NAME}_${VERSION}_${ARCH}.deb" "$BUILD_DIR/"

echo ""
echo "Package built successfully:"
echo "  $BUILD_DIR/${PACKAGE_NAME}_${VERSION}_${ARCH}.deb"
echo ""
echo "To install:"
echo "  sudo dpkg -i ${PACKAGE_NAME}_${VERSION}_${ARCH}.deb"
echo "  sudo apt-get install -f  # Install dependencies if needed"
echo ""

