Thorn Tech Marketing Ad
Skip to main content
Version: 1.4.0

Running the In-Place Upgrade Script to v1.4.0

TLDR

What: Upgrade a single-instance StorageLink 1.3.0 or 1.3.1 to 1.4.0 in place

Requirement: The instance must be on 1.3.0 or 1.3.1. Instances on 1.2.1 or earlier have no license and are refused; move them to a new instance with a backup instead

Command: cd ~ && curl -sS -O https://thorntech-products.s3.amazonaws.com/storagelink/1.004.00/in-place-upgrade-storagelink.sh && sudo bash ./in-place-upgrade-storagelink.sh

Important: Export a backup file first; read Action required before upgrading in the Release Notes; work through After the Upgrade

Overview​

This article goes over how to run the in-place upgrade script to upgrade an existing StorageLink 1.3.0 or 1.3.1 instance to version 1.4.0 (1.004.00). The Release Notes list what changed.

Note: The script only applies to instances on 1.3.0 or 1.3.1. Licensing arrived in 1.3.0, so an instance on 1.2.1 or earlier has no license, and an upgrade in place would leave it unlicensed. The script refuses those instances before changing anything. To upgrade one, deploy a new 1.4.0 instance and import a backup, as described in the Upgrade Process article. Contact support@thorntech.com first if the instance has more than 10 users or legacy pricing, so that a license covering them is ready.

Your license carries forward. It is stored in the database, bound to this instance, and the script does not touch it.

Important Mentions​

Make a new Backup File​

Our recommended approach for upgrading is to deploy a new StorageLink instance and import your Users & Settings into it with a Backup file, as described in the Upgrade Process article. You can export a new Backup file under Settings ---> Backup & Recovery ---> Export Backup File.

The script exists for convenience; the safest approach is the one above. Before running it, export a new Backup file. The script also writes its own rollback bundle (a database dump and the files it replaces) to /var/backups/slink-upgrade-<stamp>/.

Action required before upgrading​

1.4.0 migrates the database at its first start, and 1.3.x cannot run on the migrated database afterwards. Read Action required before upgrading in the Release Notes first. In short:

  • The script stops if two folders under the same parent share a name, and lists them. Rename one of each pair, or contact support.
  • Administrators without a password can sign in after the upgrade only through an identity provider typed Admin User. The script names them and continues.
  • features.api.file-upload-accept-rules is retired. If your instance sets it, the first start turns it into a file-type rule on the root folder.

LetsEncrypt and custom SSL certificates​

If you used LetsEncrypt or installed your own certificate, edit the new website.conf after the upgrade: the script installs a new one and keeps yours as website.conf-<stamp> in the same directory. Copy the server_name, ssl_certificate and ssl_certificate_key lines across, then run sudo nginx -t && sudo systemctl restart nginx.

The script carries one setting over on its own: the frame-ancestors value that launch wrote from FRAME_ANCESTORS, so an instance embedded in another site stays embeddable. If your file had any other change, the script says so, prints the difference between your file and the new one, and waits for you to press Enter before it goes on. The file is located here:

AWS:

/etc/nginx/conf.d/website.conf

Azure and Google Cloud:

/etc/nginx/sites-available/website.conf

Check out the Troubleshooting section of the LetsEncrypt article to see what the file should look like.

Memory Settings​

The script sizes the Java heap from the VM's RAM in /opt/swiftgw/swiftgateway-1.4.0.conf. If you resize the VM later, use the Memory Settings article.

Troubleshooting​

The script stops with cannot be upgraded in place. The instance is on 1.2.1 or earlier and nothing has been changed. See the note in the Overview.

The script stops with backend did not become healthy in 10 minutes. The service is left running and may still be starting; the first start migrates the database. Check sudo systemctl status swiftgateway and the most recent application log (the date is in the name):

/opt/swiftgw/log/application-2026-11-04.log

If you become stuck at the Please wait while StorageLink finishes setting up loading screen, or need to roll back, contact us at support@thorntech.com and send the script output and that log. The rollback bundle for each run is in /var/backups/slink-upgrade-<stamp>/.

Edge cases​

Restricted networks, high availability, load balancers, nginx validation, rolling back

No outbound internet access. The script downloads the 1.4.0 files from https://thorntech-products.s3.amazonaws.com, and installs Java 21 or unzip from your operating system's package repositories only if they are missing. An instance without outbound HTTPS access cannot run it; use the backup-and-restore path in the Upgrade Process article instead.

High-availability deployments. Do not run the script on a high-availability deployment; contact support@thorntech.com for the upgrade path.

Behind a load balancer or reverse proxy. Nothing to do. The trusted-proxy setting (security.client-ip.trusted-proxies) that StorageLink 1.3.0 introduced is already in place on a 1.3.x instance, and the script leaves your existing properties alone.

nginx validation. The script refuses to start if your current nginx configuration fails nginx -t, and tells you so; fix the file it names and run the script again. If the new website.conf fails validation, the script restores your previous one, keeps the new one as website.conf-1.4.0-failed in the same directory, and continues. Send both files to support if that happens.

StorageLink does not start after the upgrade. One known cause: security.max-login-failed-attempts or security.failed-login-timeout-seconds set below 1 in /opt/swiftgw/application.properties. The startup error in the application log names the property; set it to 1 or more and run sudo systemctl restart swiftgateway.

Rolling back. Each run writes /var/backups/slink-upgrade-<stamp>/ with pg_dumpall.sql (the database before the upgrade), opt-swiftgw.tgz (the previous /opt/swiftgw), and the previous swiftgateway.service, website.conf and application.properties. The previous jar also stays in /opt/swiftgw/. 1.4.0 migrates the database at its first start, so a rollback restores the SQL dump as well as the files. Contact support@thorntech.com before rolling back and we will walk through it with you.

Running the Script​

SSH into the VM (see SSH into the VM).

Download the script into your home directory:

cd ~
curl -sS -O https://thorntech-products.s3.amazonaws.com/storagelink/1.004.00/in-place-upgrade-storagelink.sh

Run it:

sudo bash ./in-place-upgrade-storagelink.sh

Run it exactly like that, with sudo bash from your home directory: /tmp is mounted noexec on the StorageLink image. The script prints every command it runs. Keep the SSH session open until it finishes; the final health check waits up to 10 minutes while the first start migrates the database. If the script stops partway, run it again. A successful run ends with:

StorageLink 1.4.0 is UP after upgrade.

Upgrade to 1.4.0 complete.
Rollback bundle: /var/backups/slink-upgrade-<stamp>

When you refresh your Web Admin UI you should see the updated UI and version 1.4.0 at the bottom.

After the Upgrade​

  1. Identity providers. Every existing provider now has Give new users a home folder turned on; turn it off where new users should get access only through groups. If a provider typed Admin User serves regular users, retype it Users only. The Release Notes explain each case.
  2. Upload accept rules. If you set features.api.file-upload-accept-rules, review the file-type rule on the root folder and remove the property from /opt/swiftgw/application.properties.
  3. Certificates. Re-apply your hostname and certificate lines to the new website.conf (see above). The frame-ancestors value is carried over for you.
  4. Log forwarding. Access-control changes are now written to the audit log, /opt/swiftgw/log/audit-<date>.log, instead of the application log; point saved queries or alerts there (see the Logging article).
  5. Clean up. Remove the rollback bundle and the stamped copies of the previous admin UI, website.conf and service definition once you are satisfied.

Script Contents​

in-place-upgrade-storagelink.sh (1.004.00)
#!/bin/bash
#
# StorageLink in-place upgrade script: upgrades a single-instance StorageLink
# 1.3.0 or 1.3.1 to v1.4.0.
#
# 1.4.0 adds storage groups, folder-level file-type restrictions, Spanish and an
# access-control audit trail. It changes the database schema: the first start of
# 1.4.0 migrates the database, and 1.3.x cannot run on the migrated database.
# The script takes a full database dump before it changes anything.
#
# Read "Action required before upgrading" in the release notes first:
# https://help.thorntech.com/storagelink/docs/general-information/release-notes
# Before it stops the service, the script checks the database and
# - refuses to continue if two folders under the same parent share a name:
# 1.4.0 requires unique sibling names and does not start on such a database;
# - warns about enabled administrators without a password: after the upgrade
# they can sign in only through an identity provider typed Admin User.
#
# Steps:
# 1. Application files: the 1.4.0 jar and conf, the web admin UI and the nginx
# site config. The systemd unit launches `java -jar` with an EnvironmentFile
# (JAVA_OPTS/RUN_ARGS) and Type=notify.
# 2. Application properties: adds any property 1.3.x requires that is missing.
# Every step is idempotent, so on most 1.3.x instances these are no-ops.
# 3. Java 21 is installed if it is missing.
#
# PostgreSQL is left at its current version; 1.4.0 enforces no minimum version.
#
# Every step can be repeated: if the script stops partway, run it again.
#
# Supported: single-instance StorageLink 1.3.0 and 1.3.1 on AWS (Amazon Linux
# 2023), Azure and Google Cloud (Ubuntu). Not for high-availability deployments.
# Instances on 1.2.1 or earlier are not upgraded in place: they have no license
# (licensing arrived in 1.3.0) and move to a new instance through a backup.
#
# QA mode: if ASSETS_TARBALL is set (a .tgz containing swiftgateway-<ver>.jar,
# swiftgateway-<ver>.conf, admin-ui/ and website.conf), it is used instead of the
# public S3 assets.zip — lets the upgrade run against pre-release builds.
#
# How to run:
# cd ~
# curl -sS -O https://thorntech-products.s3.amazonaws.com/storagelink/1.004.00/in-place-upgrade-storagelink.sh
# sudo bash ./in-place-upgrade-storagelink.sh
#
# Run it with "sudo bash" from your home directory: /tmp is mounted noexec on
# the hardened appliance, so "sudo ./in-place-upgrade-storagelink.sh" from /tmp
# fails with "Permission denied".
#

set -xe

if [[ $(whoami) != "root" ]]; then
echo "Usage: sudo bash $0"
exit 1
fi

TARGET_VERSION="${TARGET_VERSION:-1.4.0}"
TARGET_VERBOSE_VERSION="1.004.00"
# One stamp per run: every backup copy and the rollback bundle carry it, so a
# re-run never overwrites the copies taken before the first attempt.
STAMP=$(date +"%m%d%Y-%H%M%S")
APPLICATION_PROPERTIES="/opt/swiftgw/application.properties"
BACKUP_DIR="/var/backups/slink-upgrade-${STAMP}"

# Wait for any other apt/dpkg holder (e.g. unattended-upgrades) instead of
# failing mid-upgrade, and never let a package replace a locally-modified
# config file via a conffile prompt (noninteractive runs die on those).
APT_OPTS=(-o DPkg::Lock::Timeout=600
-o Dpkg::Options::=--force-confdef
-o Dpkg::Options::=--force-confold)

function extractPropValueFromSourceFile {
local prefix="${1}"
local str=`grep "${prefix}" ${2} 2>/dev/null`
echo "${str#$prefix}" | xargs
}

#
# 0. Preflight
#

# Source version: the jar currently installed (the newest one that is not the
# target). Drives the licensing message below and the health-wait hint later.
CURRENT_JAR=$(ls /opt/swiftgw/swiftgateway-*.jar 2>/dev/null | grep -v "swiftgateway-${TARGET_VERSION}.jar" | sort -V | tail -1 || true)
SOURCE_VERSION=$(basename "${CURRENT_JAR:-swiftgateway-unknown.jar}" .jar); SOURCE_VERSION="${SOURCE_VERSION#swiftgateway-}"
echo "Upgrading StorageLink ${SOURCE_VERSION} -> ${TARGET_VERSION}"

# 1.4.0 upgrades 1.3.x only. Anything older has no license and would come up
# unlicensed after an in-place upgrade, so stop before changing anything.
if [[ "${SOURCE_VERSION}" != 1.3* ]]; then
echo "ERROR: StorageLink ${SOURCE_VERSION} cannot be upgraded in place (this script needs 1.3.0 or 1.3.1). Nothing has been changed." >&2
echo "Versions before 1.3.0 have no license, so an in-place upgrade would leave this instance unlicensed." >&2
echo "Move to a new ${TARGET_VERSION} instance with a backup instead; contact support@thorntech.com first if you have more than 10 users or legacy pricing:" >&2
echo " https://help.thorntech.com/storagelink/docs/backup-migration-update/upgrade" >&2
exit 1
fi
# The license is stored in the database, bound to this instance's cluster ID,
# and nothing here touches it.
echo "1.3.x source: the existing license carries forward unchanged."

# Pre-flight: the database. Both checks only read it.
DB_NAME=$(extractPropValueFromSourceFile "spring.datasource.url=" ${APPLICATION_PROPERTIES})
DB_NAME="${DB_NAME##*/}"; DB_NAME="${DB_NAME%%\?*}"; DB_NAME="${DB_NAME:-swiftgw}"
function psql_read {
sudo -u postgres psql -d "${DB_NAME}" -tA -v ON_ERROR_STOP=1 -c "$1"
}

# 1.4.0 requires folder names to be unique under each parent and does not start
# on a database that holds two siblings with the same name.
DUPLICATE_FOLDERS=$(psql_read "select p.absolute_path || ' : ' || f.name || ' (' || count(*) || ' folders)' from folder f join folder p on p.id = f.parent_id where f.name is not null group by p.absolute_path, f.parent_id, f.name having count(*) > 1 order by 1")
if [ -n "${DUPLICATE_FOLDERS}" ]; then
echo "" >&2
echo "ERROR: these folders share a name with another folder under the same parent (parent : name):" >&2
echo "${DUPLICATE_FOLDERS}" >&2
echo "StorageLink 1.4.0 requires unique folder names under each parent and would not start on this database." >&2
echo "The upgrade has NOT started and nothing has been changed. Contact support before upgrading." >&2
exit 1
fi

# Administrators without a password can sign in after the upgrade only through
# an identity provider typed Admin User (release notes, Action required).
ADMIN_FILTER="a.authority in ('ROLE_ADMIN','ROLE_SYSTEM_ADMIN') and u.enabled"
NO_PASSWORD="coalesce(btrim(u.password, E' \\t\\n\\r'), '') = ''"
ADMINS_WITHOUT_PASSWORD=$(psql_read "select distinct u.username from users u join authorities a on a.user_id = u.id where ${ADMIN_FILTER} and ${NO_PASSWORD} order by 1")
ADMINS_WITH_PASSWORD=$(psql_read "select count(distinct u.id) from users u join authorities a on a.user_id = u.id where ${ADMIN_FILTER} and not (${NO_PASSWORD})")
if [ -n "${ADMINS_WITHOUT_PASSWORD}" ]; then
echo "WARNING: these enabled administrators have no password:"
echo "${ADMINS_WITHOUT_PASSWORD}"
echo "After the upgrade they can sign in only through an identity provider typed Admin User."
if [ "${ADMINS_WITH_PASSWORD}" == "0" ]; then
echo "WARNING: no enabled administrator has a password. Unless an identity provider typed"
echo "Admin User admits them, the installation loses administration. Contact support first."
fi
echo "See Action required before upgrading in the release notes."
fi

mkdir -p "${BACKUP_DIR}"

# Determine cloud provider (same probe order as prior scripts)
# head -c keeps a wrong-cloud error page (e.g. Google's HTML 404) from
# flooding the trace log — the real values are all short strings.
AWS_DOMAIN=$(curl -s --max-time 2 "http://169.254.169.254/latest/meta-data/services/domain" | head -c 40 || true)
AZURE_DOMAIN=$(curl --noproxy "*" --max-time 2 -s -H 'Metadata: True' "http://169.254.169.254/metadata/instance/compute/azEnvironment?api-version=2019-06-01&format=text" | head -c 40 || true)
GCP_CHECK=$(curl -s --max-time 2 "http://169.254.169.254/computeMetadata/v1/instance/zone" -H "Metadata-Flavor: Google" | head -c 80 || true)
CLOUD_PROVIDER=aws
# GCP's metadata answer contains "zones/..." — other clouds' IMDS return XML/JSON errors here
[[ $GCP_CHECK == *"zones/"* ]] && CLOUD_PROVIDER=gcp
[[ $AWS_DOMAIN == "amazonaws.com" ]] && CLOUD_PROVIDER=aws
[[ $AZURE_DOMAIN == "AzurePublicCloud" ]] && CLOUD_PROVIDER=azure

# Determine OS and nginx layout
if getent passwd www-data > /dev/null 2>&1; then
OS=ubuntu
NGINX_USER=www-data
NGINX_CONF_PATH="/etc/nginx/sites-available"
else
OS=el
NGINX_USER=nginx
NGINX_CONF_PATH="/etc/nginx/conf.d"
fi

# unzip is needed to unpack the assets bundle; not every image ships it.
if ! command -v unzip >/dev/null 2>&1; then
if [ "$OS" == "ubuntu" ]; then
apt-get "${APT_OPTS[@]}" update
DEBIAN_FRONTEND=noninteractive apt-get "${APT_OPTS[@]}" install -y -q unzip
else
yum install -y unzip
fi
fi

# Pre-flight: refuse to start if the CURRENT nginx config already fails
# validation. This upgrade stops the app — never begin that on a box whose
# web tier is already broken.
if ! nginx -t; then
echo "" >&2
echo "ERROR: 'nginx -t' fails on this instance's CURRENT nginx configuration." >&2
echo "The upgrade has NOT started and nothing has been changed." >&2
echo "Fix the nginx configuration (run 'sudo nginx -t' to see the error), then re-run this script." >&2
exit 1
fi

#
# 1. Backups (rollback bundle)
#

# Full logical DB backup. The script itself does not modify the database, but
# the first start of 1.4.0 migrates it and 1.3.x cannot run on the result: this
# dump is the way back.
sudo -u postgres pg_dumpall > "${BACKUP_DIR}/pg_dumpall.sql"

# App + config backups
tar czf "${BACKUP_DIR}/opt-swiftgw.tgz" --exclude='swiftgw/tmp/*' --exclude='swiftgw/log/*' -C /opt swiftgw
cp -a /etc/systemd/system/swiftgateway.service "${BACKUP_DIR}/swiftgateway.service"
cp -a "${NGINX_CONF_PATH}/website.conf" "${BACKUP_DIR}/website.conf" 2>/dev/null || \
cp -a /etc/nginx/sites-enabled/website.conf "${BACKUP_DIR}/website.conf" 2>/dev/null || true
echo "Rollback bundle written to ${BACKUP_DIR}"

#
# 2. Stop the application
#

systemctl stop swiftgateway

#
# 3. Java 21 runtime (1.3.x images already ship it; installed if missing)
#

if ! java -version 2>&1 | grep -q 'version "21'; then
if [ "$OS" == "ubuntu" ]; then
apt-get "${APT_OPTS[@]}" update
DEBIAN_FRONTEND=noninteractive apt-get "${APT_OPTS[@]}" install -y -q openjdk-21-jre-headless
update-alternatives --set java /usr/lib/jvm/java-21-openjdk-amd64/bin/java || true
else
yum install -y java-21-amazon-corretto
/usr/sbin/update-alternatives --set java /usr/lib/jvm/java-21-amazon-corretto.x86_64/bin/java
fi
fi

#
# 4. Install StorageLink ${TARGET_VERSION} files
#

cd /tmp
rm -rf /tmp/slink-upgrade-assets && mkdir /tmp/slink-upgrade-assets && cd /tmp/slink-upgrade-assets
if [ -n "${ASSETS_TARBALL}" ] && [ -f "${ASSETS_TARBALL}" ]; then
tar xzf "${ASSETS_TARBALL}"
else
curl -fsSL -o assets.zip "https://thorntech-products.s3.amazonaws.com/storagelink/${TARGET_VERBOSE_VERSION}/assets.zip"
# Normalize the zip's assets/ folder to the same top-level layout the
# ASSETS_TARBALL path produces — later steps (website.conf install) resolve
# files relative to /tmp/slink-upgrade-assets and would miss assets/.
unzip -o assets.zip && mv assets/* . && rmdir assets
fi

# jar + conf
chmod +x swiftgateway-${TARGET_VERSION}.jar
chown swiftgw:swiftgw swiftgateway-${TARGET_VERSION}.jar swiftgateway-${TARGET_VERSION}.conf
mv swiftgateway-${TARGET_VERSION}.jar swiftgateway-${TARGET_VERSION}.conf /opt/swiftgw/

# Heap sizing: the conf ships with values computed for the build VM; recompute
# for this instance like first-boot does (Xms ~15% / Xmx ~48% of MemTotal).
MEM_MB=$(awk '/MemTotal/ {printf "%d", $2/1024}' /proc/meminfo)
XMS=$((MEM_MB * 15 / 100))
XMX=$((MEM_MB * 48 / 100))
sed -i -E "s/-Xms[0-9]+m/-Xms${XMS}m/; s/-Xmx[0-9]+m/-Xmx${XMX}m/" /opt/swiftgw/swiftgateway-${TARGET_VERSION}.conf

# admin UI (previous UI kept as admin-ui-<stamp>)
if [ -d admin-ui ]; then
tar czf /usr/share/nginx/admin-ui.tar.gz admin-ui
else
mv admin-ui.tar.gz /usr/share/nginx
fi
cd /usr/share/nginx
[ -d admin-ui ] && mv admin-ui "admin-ui-${STAMP}"
tar xzvpf admin-ui.tar.gz && rm -f admin-ui.tar.gz
# Drop macOS AppleDouble metadata files (._*) if the bundle was built on a Mac.
find admin-ui -name '._*' -delete
chown -R ${NGINX_USER}:${NGINX_USER} admin-ui

# nginx site config (backup already taken; certs keep their existing paths)
cd /tmp/slink-upgrade-assets
if [ -f website.conf ]; then
OLD_CONF="${NGINX_CONF_PATH}/website.conf"
# Carry the frame-ancestors value over from the file nginx was serving: first
# boot wrote it there from FRAME_ANCESTORS, and user data does not run again.
OLD_FA=$(sed -nE 's/^[[:space:]]*add_header Content-Security-Policy "frame-ancestors ([^"]*)".*/\1/p' "${OLD_CONF}" 2>/dev/null | head -1)
if [ -n "${OLD_FA}" ]; then
FA_ESCAPED=$(printf '%s' "${OLD_FA}" | sed -e 's/[\\&|]/\\&/g')
sed -i -E "s|^([[:space:]]*add_header Content-Security-Policy \"frame-ancestors )[^\"]*(\".*)|\1${FA_ESCAPED}\2|" website.conf
fi
# Any other change to the old file is lost when it is replaced. Detect that by
# comparing it, with the frame-ancestors value blanked, against the fingerprint
# of the website.conf shipped in that release's assets.zip.
case "${SOURCE_VERSION}" in
1.3.0|1.3.1) SHIPPED_SHA=1bf30958962fd9d39ea1af735bfc4fe88cf83659ae7def9cc0652cba072520f5 ;;
1.4.0) SHIPPED_SHA=a01b36f0ec2d8db12e3dca9d6cccc823bd4e8e8d4dcd18717cdd88a939714953 ;;
*) SHIPPED_SHA=unknown ;;
esac
OLD_SHA=$( { [ -f "${OLD_CONF}" ] && sed -E 's/(frame-ancestors )[^"]*/\1X/' "${OLD_CONF}" | sha256sum | cut -d' ' -f1; } || echo missing)
cp "${OLD_CONF}" "${NGINX_CONF_PATH}/website.conf-${STAMP}" 2>/dev/null || true
chown ${NGINX_USER}:${NGINX_USER} website.conf
mv website.conf "${OLD_CONF}"
if [ "${OLD_SHA}" != "missing" ] && [ "${OLD_SHA}" != "${SHIPPED_SHA}" ]; then
{ set +x; } 2>/dev/null
echo "" >&2
echo "WARNING: ${OLD_CONF} had been changed since ${SOURCE_VERSION} was installed, and has been REPLACED by the ${TARGET_VERSION} file." >&2
echo "Your previous file is kept at ${NGINX_CONF_PATH}/website.conf-${STAMP} (and in ${BACKUP_DIR}/website.conf)." >&2
echo "The frame-ancestors value was carried over. Apply any other change again after the upgrade. This is the difference:" >&2
diff -u "${NGINX_CONF_PATH}/website.conf-${STAMP}" "${OLD_CONF}" >&2 || true
echo "" >&2
if [ -t 0 ]; then read -r -p "Press Enter to continue the upgrade. " _; fi
set -x
fi
# Validate the new config immediately. Don't abort — restore the previous
# (working) config, keep the failing one for inspection, and continue loudly.
if ! nginx -t; then
echo "ERROR: new website.conf fails 'nginx -t' — restoring the previous config." >&2
mv "${NGINX_CONF_PATH}/website.conf" "${NGINX_CONF_PATH}/website.conf-${TARGET_VERSION}-failed"
cp "${BACKUP_DIR}/website.conf" "${NGINX_CONF_PATH}/website.conf"
nginx -t
fi
fi

# webconfig.js — preserve this instance's OAuth client
# The OAuth client values are served publicly in webconfig.js by design, but
# keep them out of this trace log — customers share these logs with support.
{ set +x; } 2>/dev/null
echo "Writing webconfig.js with this instance's OAuth client (values not logged)"
CLIENT_ID=$(extractPropValueFromSourceFile "security.client-id=" ${APPLICATION_PROPERTIES})
CLIENT_SECRET=$(extractPropValueFromSourceFile "security.client-secret=" ${APPLICATION_PROPERTIES})
(
cat <<EOF
window._env_ = {
"clientid": "$CLIENT_ID",
"clientsecret": "$CLIENT_SECRET",
"cloudProvider": "$CLOUD_PROVIDER",
"version": "${TARGET_VERSION%%-*}"
};
EOF
) | tee /usr/share/nginx/admin-ui/webconfig.js >/dev/null
chown ${NGINX_USER}:${NGINX_USER} /usr/share/nginx/admin-ui/webconfig.js
set -x

#
# 5. application.properties — add the 1.3.x-required properties (idempotent; no-ops on a 1.3.0 source)
#

function ensure_prop {
local key="$1" value="$2"
grep -q "^${key}=" "${APPLICATION_PROPERTIES}" || \
echo "${key}=${value}" >> "${APPLICATION_PROPERTIES}"
}

cp -a "${APPLICATION_PROPERTIES}" "${BACKUP_DIR}/application.properties"
# Required for the Type=notify systemd unit — without it the service never
# signals readiness and systemd kills it at TimeoutSec.
ensure_prop "features.systemd.notify" "true"
# 1.3.x resolves the client address itself (security.client-ip.trusted-proxies)
# and rebuilds proxied URLs from security.redirect.base-path, so Spring's own
# forwarded-header handling must be off. 1.2.x set this to "framework"; on
# 1.3.x any value other than "none" is logged as an error at startup and
# bypasses the trusted-proxy resolution, so replace whatever is there.
# Leave the file untouched when it is already correct (1.3.x sources), so a
# re-run or a 1.3.0 -> 1.3.1 upgrade does not reorder application.properties.
if ! grep -q '^server\.forward-headers-strategy=none$' "${APPLICATION_PROPERTIES}"; then
sed -i '/^server\.forward-headers-strategy=/d' "${APPLICATION_PROPERTIES}"
ensure_prop "server.forward-headers-strategy" "none"
fi
ensure_prop "security.redirect.base-path" "backend/"
ensure_prop "server.max-http-request-header-size" "128KB"
# features.api.file-upload-accept-rules is retired in 1.4.0 and is no longer
# added. A value that is already set becomes an Allowlist on the root folder at
# the first start (release notes, Action required).
chown swiftgw:swiftgw "${APPLICATION_PROPERTIES}"

#
# 6. systemd unit — Spring Boot 4 launch pattern
#

cp -a /etc/systemd/system/swiftgateway.service "/etc/systemd/system/swiftgateway.service-${STAMP}"
cat > /etc/systemd/system/swiftgateway.service <<EOF
[Unit]
Description=StorageLink
After=syslog.target network.target
Before=nginx.service

[Service]
Type=notify
User=swiftgw
WorkingDirectory=/opt/swiftgw
EnvironmentFile=-/opt/swiftgw/swiftgateway-${TARGET_VERSION}.conf
ExecStart=/usr/bin/java \$JAVA_OPTS -jar /opt/swiftgw/swiftgateway-${TARGET_VERSION}.jar \$RUN_ARGS
SuccessExitStatus=143
AmbientCapabilities=CAP_NET_BIND_SERVICE
NotifyAccess=all
TimeoutSec=900

[Install]
WantedBy=multi-user.target
EOF

# Login banner version
sed -i "s/1\..*/${TARGET_VERSION}/" /etc/profile.d/login-info.sh 2>/dev/null || true

#
# 7. Restart everything and wait for health
#

if nginx -t; then
systemctl restart nginx
else
echo "WARNING: nginx config fails validation — nginx NOT restarted (see errors above)." >&2
fi
systemctl daemon-reload
systemctl start swiftgateway

# The first start of 1.4.0 migrates the database, so allow up to 10 minutes on
# small VMs; the backend is normally UP within a couple of minutes.
for i in $(seq 1 120); do
sleep 5
if curl -sk --max-time 5 http://127.0.0.1:8080/actuator/health | grep -q '"UP"'; then
echo "StorageLink ${TARGET_VERSION} is UP after upgrade."
break
fi
if [ "$i" == "120" ]; then
echo "ERROR: backend did not become healthy in 10 minutes"
echo "The service was left running and may still be starting. Check 'systemctl status swiftgateway'"
echo "and 'journalctl -u swiftgateway'. Once the cause is fixed it is safe to run this script again."
journalctl -u swiftgateway --no-pager | tail -40
exit 1
fi
done

echo
echo "Upgrade to ${TARGET_VERSION} complete."
echo "Rollback bundle: ${BACKUP_DIR}"
echo "PostgreSQL was left at its current version. The database was migrated to ${TARGET_VERSION} at the first start;"
echo "the pre-upgrade dump is ${BACKUP_DIR}/pg_dumpall.sql (1.3.x cannot run on the migrated database)."
echo "License: carried forward from ${SOURCE_VERSION} (nothing to do)."
echo "Previous application files are kept for rollback: ${CURRENT_JAR:-<none>} and ${BACKUP_DIR}."