#!/usr/bin/env bash
set -euo pipefail

[ -f ./.env ] || { echo "Error: .env file not found"; exit 1; }
source ./.env || { echo "Error: failed to load .env"; exit 1; }

command -v fpm >/dev/null 2>&1 || { echo "Error: fpm not found in PATH"; exit 1; }

rm -rf ./build
rm -f "${BUILD_APP}_${BUILD_VER}_${BUILD_ARCH}.deb"

rm -rf "$BUILD_STAGE"
mkdir -p "$BUILD_STAGE"/{opt/$BUILD_APP,usr/bin,var/log/$BUILD_APP}

for item in *; do
  [ "$item" = "build" ] && continue
  case "$item" in
    .*|*.deb) continue ;;
  esac
  cp -a "$item" "$BUILD_STAGE/opt/$BUILD_APP/" || { echo "Error: failed to copy '$item' to stage"; exit 1; }
done

touch "$BUILD_STAGE/var/log/$BUILD_APP/app.log" || { echo "Error: unable to create log in $BUILD_STAGE/var/log/$BUILD_APP"; exit 1; }
cat > "$BUILD_STAGE/usr/bin/$BUILD_APP" <<EOF
#!/usr/bin/env bash
exec php -S 127.0.0.1:8000 -t /opt/$BUILD_APP/public
EOF
chmod +x "$BUILD_STAGE/usr/bin/$BUILD_APP" || { echo "Error: unable to mark wrapper as executable"; exit 1; }

echo "[ok] stage ready at: $BUILD_STAGE"

FPM_DEPENDS=()
if [ -n "${BUILD_DEPENDS:-}" ]; then
  IFS=',' read -ra __DEPS <<< "$BUILD_DEPENDS"
  for d in "${__DEPS[@]}"; do
    d_trim="$(echo "$d" | xargs)"
    [ -n "$d_trim" ] && FPM_DEPENDS+=(--depends "$d_trim")
  done
fi

fpm -s dir -t deb \
  -n "$BUILD_APP" -v "$BUILD_VER" \
  -C "$BUILD_STAGE" \
  --prefix / \
  --description "$BUILD_DESCRIPTION" \
  --license "$BUILD_LICENSE" \
  --vendor "$BUILD_VENDOR" \
  --maintainer "$BUILD_MAINTAINER" \
  --architecture "$BUILD_ARCH" \
  --deb-no-default-config-files \
  "${FPM_DEPENDS[@]}" \
  opt/$BUILD_APP var/log/$BUILD_APP usr/bin/$BUILD_APP \
  || { echo "Error: fpm failed to build the package"; exit 1; }