#!/bin/sh

platform=linux-amd64
gitea_bin=/usr/local/bin/gitea
tmp_dir="$(mktemp -d /tmp/update_gitea_XXXXX)"

msg()
{
    printf '\033[32mINFO\t%s\033[0m\n' "$*"
}

err()
{
    printf '\033[31mERROR\t%s\033[0m\n' "$*"
    exit 1
}

cleanup()
{
    msg Clean up temporary data.
    [ -d "$tmp_dir" ] && rm -rf "$tmp_dir"
}

errexit()
{
    if [ "$?" -eq 0 ]; then
        cleanup
        exit 0
    else
        cleanup
        err Exiting with non-zero exit code.
    fi
}

is_outdated()
{
    # Return 1 if Gitea is up to date.
    # Return 0 if Gitea binary is outdated.

    [ -x "$gitea_bin" ] || err "$gitea_bin": file not exists or not executable

    current="$("$gitea_bin" --version | awk '{print $3}')"
    latest="$(
        curl -sSo /dev/null -w '%{redirect_url}' \
        https://github.com/go-gitea/gitea/releases/latest |
        cut -d / -f 8 | sed s/v//
    )"

    msg Current version is "${current:-ERROR}"
    msg Latest version is "$latest"

    if [ "$current" = "$latest" ]; then
        return 1
    else
        return 0
    fi
}

set -e
trap errexit EXIT
trap cleanup INT HUP TERM

if ! is_outdated; then
    msg Gitea is up to date! Exiting.
    exit 0
fi

msg Download Gitea binary
cd "$tmp_dir" || err Cannot change directory to "$tmp_dir".
wget "https://dl.gitea.com/gitea/$latest/gitea-$latest-$platform"
wget "https://dl.gitea.com/gitea/$latest/gitea-$latest-$platform.asc"
wget "https://dl.gitea.com/gitea/$latest/gitea-$latest-$platform.sha256"

msg Verify binary
sha256sum "gitea-$latest-$platform" | tee "gitea-$latest-$platform.sha256.my"
if ! diff \
    "gitea-$latest-$platform.sha256" "gitea-$latest-$platform.sha256.my"; then
    err Gitea binary is corrupted, please try again.
fi
gpg --keyserver keys.openpgp.org --recv 7C9E68152594688862D62AF62D9AE806EC1592E2
if ! gpg --verify "gitea-$latest-$platform.asc" "gitea-$latest-$platform"; then
    err 'Wrong GPG signature, please refer to' \
        'https://docs.gitea.io/en-us/install-from-binary/#verify-gpg-signature'
fi

msg Stop Gitea
systemctl stop gitea.service && msg gitea.service is stopped

msg Install new Gitea binary
install -vDm755 "gitea-$latest-$platform" "$(dirname "$gitea_bin")/gitea-$latest"
ln -vfrs "$(dirname "$gitea_bin")/gitea-$latest" "$gitea_bin"

msg Start Gitea
systemctl start gitea.service
sleep 1
if systemctl is-active gitea.service >/dev/null 2>&1; then
    msg gitea.service is started
    systemctl status --no-pager --lines=0 gitea.service
else
    systemctl status --no-pager gitea.service
fi

msg Gitea is successfully updated!