#!/bin/bash
set -euo pipefail
PACKAGE_NAME=openide
PACKAGE_VERSION=2025.2.4
PACKAGE_REL=3
PACKAGE_DESC='IDE for Java'
URL=https://download.openide.ru/252.27397.103.1/openIDE-252.27397.103.1.tar.gz
ARCHIVE=openIDE-252.27397.103.1.tar.gz
#----
CY='\e[1;33m'
NC='\033[0m'
function title() {
  echo -e "$CY──┤ $1 ├──$NC"
}
#----

title 'CREATE DIRS'
install -dm 755 package/opt/OpenIDE
install -dm 755 package/usr/bin
install -dm 755 package/usr/share/applications
install -dm 755 package/usr/share/pixmaps
install -dm 755 package/usr/share/licenses/openide
install -dm 755 package/usr/share/doc/openide

title 'DOWNLOAD ARCHIVE'
if [[ ! -e ../$ARCHIVE ]]
then
  wget $URl ../$ARCHIVE
else
  echo 'SKIP'
fi

title 'UNPACK ARCHIVE'
tar -xf ../$ARCHIVE -C package/opt/OpenIDE --strip-component=1

title 'MOVE LICENSE FILES'
mv package/opt/OpenIDE/license/* package/usr/share/licenses/openide/
rmdir package/opt/OpenIDE/license

title 'MOVE DOCS FILES'
mv package/opt/OpenIDE/build.txt \
  package/opt/OpenIDE/Install-Linux-tar.txt \
  package/opt/OpenIDE/LICENSE.txt \
  package/opt/OpenIDE/NOTICE.txt \
  package/usr/share/doc/openide/

title 'CREATE LINK LAUNCHER'
ln -s /opt/OpenIDE/bin/openide package/usr/bin/openide 

title 'COPY .desktop FILES'
install -m 644 openide.desktop package/usr/share/applications/openide.desktop
install -m 644 package/opt/OpenIDE/bin/openide.png package/usr/share/pixmaps/openide.png

title 'GENERATE control FILE'
install -dm 755 package/DEBIAN
PACKAGE_SIZE=$(( $(du -ks package/opt | cut -f1) + $(du -ks package/usr | cut -f1) ))
sed "s/__PACKAGE_NAME__/$PACKAGE_NAME/" control | \
sed "s/__PACKAGE_VERSION__/$PACKAGE_VERSION/" | \
sed "s/__PACKAGE_REL__/$PACKAGE_REL/" | \
sed "s/__PACKAGE_DESC__/$PACKAGE_DESC/" | \
sed "s/__PACKAGE_SIZE__/$PACKAGE_SIZE/" > package/DEBIAN/control

title 'BUILD PACKAGE'
dpkg-deb --build ./package $PACKAGE_NAME-$PACKAGE_VERSION-$PACKAGE_REL.deb
chown 1000:1000 $PACKAGE_NAME-$PACKAGE_VERSION-$PACKAGE_REL.deb

title 'CLEAR'
rm -rf package/
