#!/bin/bash

function mkdeb_package(){
 function skip(){ true; };
 function preinstall(){
  sudo apt-get install dpkg debconf debhelper lintian;
  sudo apt-get install devscripts debsums;
 };
 function make_checksum(){
  local dir="$1";
  pushd $dir && {
   local check="DEBIAN/md5sums";
   local files="$(find * -type f | grep -v 'DEBIAN/' | grep 'usr/')";
   [ -e $check ] && rm -f $check;
   md5sum $files | tee $check;
  };
  popd;
 };
 function pack_version(){
  local date="$(date +%Y%m%d)";
  local self="$(basename ${BASH_SOURCE[0]})";
  local arch="${package}_${version}_${date}_${architecture}.tar.xz";
  [ -e $arch ] && { rm -f $arch; sleep 1; };
  tar -cpJf $arch $self ${package}/*;
 };
 function set_param_control(){
  local name="$1"; local value="$2"; local target="$3";
  sed -i -e "s/^${name}: .*$/${name}: ${value}/" $target;
 };
 local workdir="$(pwd)";
 local package="daqgroup-lazpaint";
 local version="7.3-1astra1";
 local architecture="amd64";
 mkdir -p $workdir/$package;
 mkdir -p $workdir/$package/DEBIAN;
 [ -e $workdir/$package/usr/bin/ ] || { echo "Missed files."; return 1; };
 [ -e $workdir/$package/usr/share/ ] || { echo "Missed files."; return 1; };
 local dirsize="$(du -ks $workdir/$package | cut -f 1)";
 set_param_control Package          $package        $workdir/$package/DEBIAN/control;
 set_param_control Version          $version        $workdir/$package/DEBIAN/control;
 set_param_control Architecture     $architecture   $workdir/$package/DEBIAN/control;
 set_param_control Installed-Size   $dirsize        $workdir/$package/DEBIAN/control;
 make_checksum $workdir/$package; 
 fakeroot dpkg-deb --build $package;
 mv $package.deb ${package}_${version}_${architecture}.deb;
 pack_version;
};
mkdeb_package;
