#! /usr/bin/env bash

export VERSION=$(grep ^version Cargo.toml | awk '{print $3}' | tr -d '"')
DIST="dist"

if [ -n "$(which podman)" ]; then
    ccli="$(which podman)"
elif [ -n "$(which docker)" ]; then
	ccli="$(which docker)"
else
  echo "Docker or Podman is not installed"
  exit 1
fi

# Clean temporary environment for build
rm -rf $DIST/psp*
# Create temporary environment for build
mkdir -p $DIST/psp_rpm
mkdir -p $DIST/psp_deb
mkdir -p $DIST/psp_release

# Windows compile
$ccli run -it --rm -v $PWD:/tmp/psp "rust:1.82.0-slim" bash -c "
cd /tmp/psp
apt update -q
apt install -yq g++-mingw-w64-x86-64
rustup toolchain install stable-x86_64-pc-windows-gnu --force-non-host
rustup target add x86_64-pc-windows-gnu
cargo build --release --target x86_64-pc-windows-gnu"

# Linux compile
$ccli run -it --rm -v $PWD:/tmp/psp "rust:1.82.0-slim" bash -c "
cd /tmp/psp
cargo build --release"

# Build RPM
$ccli run -it --rm -v $PWD:/tmp/psp -v ./$DIST/psp_rpm:/tmp/psp_rpm -v ./$DIST/psp_release:/tmp/psp_release -e "VERSION=${VERSION}" "rockylinux:9.3" bash -c "
chmod 777 /tmp/psp_rpm -R
cat >/tmp/psp_rpm/psp.spec <<EOL
Name:           psp
Version:        ${VERSION}
Release:        1
Summary:        (Python Scaffolding Projects)
BuildArch:      x86_64
License:        Apache License 2.0
URL:            https://github.com/MatteoGuadrini/psp
Source0:        %{name}-%{version}.tar.gz
Requires:       bash

%global _description %{expand:
PSP (Python Scaffolding Projects).}

%description %{_description}

%prep
%setup -q

%install
rm -rf %{buildroot}
mkdir -p %{buildroot}/%{_bindir}
cp %{name} %{buildroot}/%{_bindir}

%files
%license LICENSE.md
%doc README.md
%{_bindir}/%{name}

%changelog
* %{__cat} CHANGES.md
EOL
dnf install rpmdevtools gcc -yq
cd /tmp/psp_rpm
mkdir -p "psp-${VERSION}"
cp /tmp/psp/target/release/psp "psp-${VERSION}/"
cp /tmp/psp/LICENSE.md "psp-${VERSION}/"
cp /tmp/psp/README.md "psp-${VERSION}/"
cp /tmp/psp/CHANGES.md "psp-${VERSION}/"
tar --create --file "psp-${VERSION}.tar.gz" "psp-${VERSION}"
rpmdev-setuptree
cp "psp-${VERSION}.tar.gz" /root/rpmbuild/SOURCES/
cp psp.spec /root/rpmbuild/SPECS/
rpmbuild -bb /root/rpmbuild/SPECS/psp.spec
mv /root/rpmbuild/RPMS/x86_64/psp-${VERSION}*.x86_64.rpm psp.rpm
cp psp.rpm /tmp/psp_release"

# Build DEB
$ccli run -it --rm -v $PWD:/tmp/psp -v ./$DIST/psp_deb:/tmp/psp_deb -v ./$DIST/psp_release:/tmp/psp_release -e "VERSION=${VERSION}" ubuntu:24.04 bash -c "
chmod 755 /tmp/psp_deb -R
mkdir -p /tmp/psp_deb/psp-${VERSION}
mkdir -p /tmp/psp_deb/psp-${VERSION}/DEBIAN
mkdir -p /tmp/psp_deb/psp-${VERSION}/usr/local/bin
cp /tmp/psp/target/release/psp "/tmp/psp_deb/psp-${VERSION}/usr/local/bin/"
cat >/tmp/psp_deb/psp-${VERSION}/DEBIAN/control <<EOL
Package: psp
Version: ${VERSION}
Maintainer: Matteo Guadrini
Architecture: all
Description: PSP (Python Scaffolding Projects)
EOL
cd /tmp/psp_deb
dpkg-deb --build "psp-${VERSION}"
mv "psp-${VERSION}.deb" psp.deb
cp psp.deb /tmp/psp_release"
