#!/bin/bash
#Service to auto update gitea installation
#Make sure curl and jq packages are installed
echo "GITEA UPDATER"

GITEA_HOME=/opt/gitea
DATE=$(date +%F-%H%M)
LOG_FILE="$GITEA_HOME/gitea-$DATE"
#Get Current Gitea Information
previousversion=$(gitea -v | awk '{print $3}')

#Get Version information from Git (This would determine if next statement if update should be run)
newversion=$(curl -s https://dl.gitea.com/gitea/version.json | jq .latest.version | sed -e 's/^"//' -e 's/"$//')

#If there's a new version - proceed to update
if [ $newversion != $previousversion ]; then

    # Go to $GITEA_HOME
    cd $GITEA_HOME

    #Make Old Version Unexecutable"
    #Current executable is placed in GITEA_HOME and symbolic linked to /usr/local/bin
    rm_chmod="chmod -x gitea"
    eval " $rm_chmod"

    #Move Old Executable
    mv_gitea="mv gitea gitea_old_$previousversion"
    eval " $mv_gitea"

    #Get System Information (Adapted to Debian - This would need changes for other OS's)
    sys=$(uname -s)
    system=$(echo $sys | tr '[:upper:]' '[:lower:]')
    archictecture=$(dpkg --print-architecture)

    #Form URL Based on system information
    url="https://dl.gitea.com/gitea/$newversion/gitea-$newversion-$system-$archictecture"

    #Download update
    command=$(curl $url -o gitea)
    eval "$command"

    #Make new version executable
    put_chmod="chmod +x gitea"
    eval "$put_chmod"

    #Restart Gitea service - allow user to run service without password
    #Service created from gitea documentation
    eval " sudo systemctl restart gitea.service"
    echo "update completed from $previousversion to newversion" >> $LOG_FILE
else

    echo "no update available" >> $LOG_FILE

fi