#!/bin/bash

set -e

print_usage() {
  echo "Usage: $0 <package-type> <target-dir>"
  echo "  package-type: Package type to build (deb, rpm, tar)"
  echo "  target-dir:   Target directory to save the package"
}

PACKAGE_TYPE=$1
TARGET_DIR=$2

if [ -z "$PACKAGE_TYPE" ] || [ -z "$TARGET_DIR" ]; then
  print_usage
  exit 1
fi

if [ "$PACKAGE_TYPE" != "deb" ] && [ "$PACKAGE_TYPE" != "rpm" ] && [ "$PACKAGE_TYPE" != "tar" ]; then
  echo "Unknown package type: $PACKAGE_TYPE"
  print_usage
  exit 1
fi

if [ ! -d "$TARGET_DIR" ]; then
  echo "Target path does not exist or is not a directory: $TARGET_DIR"
  exit 1
fi

if [ ! -w "$TARGET_DIR" ]; then
  echo "Target path is not writable: $TARGET_DIR"
  exit 1
fi

TARGET_DIR=$(realpath $TARGET_DIR)

BUILDDIR=$(mktemp --tmpdir -d imgproxy.XXXXXXXX)
trap "rm -rf $BUILDDIR" EXIT

echo
echo "Building in $BUILDDIR, target path: $TARGET_DIR"

cd $BUILDDIR

# ==============================================================================
# Copy the package content

echo
echo "Copying the package content..."

mkdir -p opt/imgproxy
mkdir -p opt/imgproxy/libexec

cp -r /opt/imgproxy/lib opt/imgproxy/
cp -r /opt/imgproxy/bin/imgproxy opt/imgproxy/libexec/

if [ -d /opt/imgproxy/share ]; then
  cp -r /opt/imgproxy/share opt/imgproxy/
fi

# ==============================================================================
# Patching RPATHs

echo
echo "Patching RPATHs..."

# Install patchelf
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends patchelf

# Patch the RPATH of the imgproxy binary
patchelf --set-rpath '$ORIGIN/../lib' opt/imgproxy/libexec/imgproxy
# Path the RPATH of the libvips shared libraries
find opt/imgproxy/lib -type f -regex '.*/[^/]*\.so\(\.[^/]*\)?' -exec patchelf --set-rpath '$ORIGIN' {} \;

# ==============================================================================
# Build the RC file

echo
echo "Building the RC files..."

mkdir -p opt/imgproxy/etc

SYS_RC_FILE=opt/imgproxy/etc/imgproxy.sys.rc

cat << 'EOF' > $SYS_RC_FILE
#!/usr/bin/env bash

set -e

# !!!DO NOT EDIT THIS FILE!!!
#
# This file is generated by the imgproxy package build script and will be
# overwritten on the next installation. Use imgproxy.rc instead.

IMGPROXY_ROOT=$(readlink -f "$(dirname $(readlink -f "$0"))/..")

EOF

# Dump all IMGPROXY_ and VIPS_ environment variables to the launch script.
# Declare them as exported variables with the default value if they are not set.

ENV_VARS=$(awk 'BEGIN{for(v in ENVIRON) if (match(v, "^(IMGPROXY_|VIPS_).+") != 0) print v}')

for VAR in $ENV_VARS; do
  # IMGPROXY_MALLOC doesn't work outside of the container
  if [ "$VAR" != "IMGPROXY_MALLOC" ]; then
    printf '%s=${%s:-%q}\n' "$VAR" "$VAR" "${!VAR}" >> $SYS_RC_FILE;
    echo "export $VAR=\${$VAR//\"/opt/imgproxy\"/\"\$IMGPROXY_ROOT\"}" >> $SYS_RC_FILE
    echo >> $SYS_RC_FILE
  fi
done

RC_FILE=opt/imgproxy/etc/imgproxy.rc

cat << 'EOF' > $RC_FILE
#!/usr/bin/env bash

set -e

# IMGPROXY CONFIGURATION FILE
# ===========================
#
# This file is sourced by the imgproxy launch script.
# You can use it to set environment variables for imgproxy using `export`:
#
#   export IMGPROXY_MAX_SRC_RESOLUTION=99
#
# See https://docs.imgproxy.net/configuration/options for more information
#

EOF

# ==============================================================================
# Build the launch script

echo
echo "Building the launch script..."

mkdir -p opt/imgproxy/bin
LAUNCH_SCRIPT=opt/imgproxy/bin/imgproxy

cat << 'EOF' > $LAUNCH_SCRIPT
#!/usr/bin/env bash
set -e

SCRIPT_DIR=$(dirname $(readlink -f "$0"))

IMGPROXY_SYS_RC=$(readlink -f "$SCRIPT_DIR/../etc/imgproxy.sys.rc")
if [ -f "$IMGPROXY_SYS_RC" ]; then
  source $IMGPROXY_SYS_RC
fi

IMGPROXY_RC=$(readlink -f "$SCRIPT_DIR/../etc/imgproxy.rc")
if [ -f "$IMGPROXY_RC" ]; then
  source $IMGPROXY_RC
fi

if [ -f "/etc/imgproxy.rc" ] && [ "$(readlink -f "/etc/imgproxy.rc")" != "$IMGPROXY_RC" ]; then
  source /etc/imgproxy.rc
fi

IMGPROXY_BIN=$(readlink -f "$SCRIPT_DIR/../libexec/imgproxy")
$IMGPROXY_BIN $@

EOF

# Make the launch script executable
chmod +x $LAUNCH_SCRIPT

# Test the launch script
echo -n "Testing the launch script... "
if $LAUNCH_SCRIPT version > /dev/null; then
  echo "Success"
else
  echo "Failed"
fi

# ==============================================================================
# Packaging

echo
echo "Packaging..."

VERSION=$(imgproxy version)
RELEASE=$(printf '%(%y%m%d%H%M)T\n' -1)

case $PACKAGE_TYPE in
  # TAR package ----------------------------------------------------------------
  tar)
    RESULT_FILE=imgproxy-$VERSION-$RELEASE.$(dpkg --print-architecture).tar.gz

    tar -czf $RESULT_FILE -C opt imgproxy
    cp $RESULT_FILE $TARGET_DIR
    ;;

  # DEB package ----------------------------------------------------------------
  deb)
    DEB_ARCH=$(dpkg --print-architecture)
    RESULT_FILE=imgproxy-$VERSION-$RELEASE.$DEB_ARCH.deb

    mkdir -p imgproxy
    mv opt imgproxy/

    mkdir -p imgproxy/usr/bin
    ln -s /opt/imgproxy/bin/imgproxy imgproxy/usr/bin/imgproxy

    mkdir -p imgproxy/DEBIAN

    cat << EOF > imgproxy/DEBIAN/control
Package: imgproxy
Version: $VERSION-$RELEASE
Section: base
Priority: optional
Architecture: $DEB_ARCH
Depends: bash, libc6, libstdc++6, fontconfig-config, ca-certificates, media-types
Maintainer: Foxes With Matches <info@imgproxy.net>
Homepage: https://imgproxy.net
Description: imgproxy
 imgproxy is a fast and secure standalone server for resizing and converting remote images.
EOF

    cat << 'EOF' > imgproxy/DEBIAN/conffiles
/opt/imgproxy/etc/imgproxy.rc
EOF

    cat << 'EOF' > imgproxy/DEBIAN/postinst
#!/bin/bash
set -e

if [ ! -f /etc/imgproxy.rc ]; then
  ln -s /opt/imgproxy/etc/imgproxy.rc /etc/imgproxy.rc
fi

echo
echo "imgproxy installed successfully!"
echo "You can edit /etc/imgproxy.rc to configure imgproxy or set imgproxy environment variables in your shell profile."
echo "See https://docs.imgproxy.net/configuration/options for more information."
EOF
    chmod +x imgproxy/DEBIAN/postinst

    cat << 'EOF' > imgproxy/DEBIAN/prerm
#!/bin/bash
set -e

if [ -d /opt/imgproxy/var ]; then
  rm -rf /opt/imgproxy/var
fi

if [ "$(readlink -f /etc/imgproxy.rc)" == "$(readlink -f /opt/imgproxy/etc/imgproxy.rc)" ]; then
  rm /etc/imgproxy.rc
fi
EOF
    chmod +x imgproxy/DEBIAN/prerm

    dpkg-deb --build imgproxy $RESULT_FILE
    cp $RESULT_FILE $TARGET_DIR
    ;;

  # RPM package ----------------------------------------------------------------
  rpm)
    DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends rpm

    RPM_ARCH=$(rpm --eval '%{_arch}')
    RESULT_FILE=imgproxy-$VERSION-$RELEASE.$RPM_ARCH.rpm

    mkdir -p rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS}
    mkdir -p rpmbuild/SOURCES/imgproxy
    mv opt rpmbuild/SOURCES/imgproxy/

    mkdir -p rpmbuild/SOURCES/imgproxy/usr/bin
    ln -s /opt/imgproxy/bin/imgproxy rpmbuild/SOURCES/imgproxy/usr/bin/imgproxy

    cat << 'EOF' > rpmbuild/SPECS/imgproxy.spec
Name: imgproxy
Version: %{version}
Release: %{release}
Summary: imgproxy
License: MIT
URL: https://imgproxy.net
Group: Applications/Internet
BuildArch: %{_arch}
AutoReqProv: no
Requires: bash
Requires: glibc
Requires: libstdc++
Requires: fontconfig
Requires: ca-certificates
Requires: shared-mime-info
Requires(interp): /bin/bash
Requires(post): /bin/bash
Requires(preun): /bin/bash

%description
imgproxy is a fast and secure standalone server for resizing and converting remote images.

%prep
mkdir -p $RPM_BUILD_ROOT
mv %{_sourcedir}/imgproxy/opt $RPM_BUILD_ROOT/opt
mv %{_sourcedir}/imgproxy/usr $RPM_BUILD_ROOT/usr

%files
/opt/imgproxy
/usr/bin/imgproxy

%config(noreplace) /opt/imgproxy/etc/imgproxy.rc

%post
if [ ! -f /etc/imgproxy.rc ]; then
  ln -s /opt/imgproxy/etc/imgproxy.rc /etc/imgproxy.rc
fi

%preun
if [ -d /opt/imgproxy/var ]; then
  rm -rf /opt/imgproxy/var
fi

if [ "$(readlink -f /etc/imgproxy.rc)" == "$(readlink -f /opt/imgproxy/etc/imgproxy.rc)" ]; then
  rm /etc/imgproxy.rc
fi

%clean
rm -rf $RPM_BUILD_ROOT

exit
EOF

    rpmbuild \
      --define "_topdir $(pwd)/rpmbuild" \
      --define "version $VERSION" \
      --define "release $RELEASE" \
      -bb rpmbuild/SPECS/imgproxy.spec

    cp rpmbuild/RPMS/$RPM_ARCH/$RESULT_FILE $TARGET_DIR
    ;;

  *)
    echo "Unknown package type: $PACKAGE_TYPE"
    print_usage
    exit 1
    ;;
esac

echo
echo "Done!"
echo "Package is saved to $(realpath "$TARGET_DIR/$RESULT_FILE")"
echo
