#!/bin/ash
#Vars
apiUrl=https://api.github.com/repos/go-gitea/gitea/releases/latest

#install Update tool
pip install install gitea-auto-update

#Get latest gitea version info
giteaver=$(python3 -c "import requests; print (requests.get('$apiUrl').json()['tag_name'])")
giteaver=${giteaver//v}


#Add gitea `git` service user
addgroup git
adduser -S -s /bin/ash -g 'Git Version Control' -h /home/git -D -G git git

#Making Gitea Folders 
mkdir -p /gitea-data
mkdir -p /var/lib/gitea/custom/public
mkdir -p /var/lib/gitea/data
mkdir -p /var/log/gitea
mkdir -p /etc/gitea

#Download Gitea binary
echo "Downloading gitea binary..."
python3 -c "import requests; url = 'https://dl.gitea.io/gitea/"$giteaver"/gitea-"$giteaver"-linux-amd64'; r = requests.get(url, allow_redirects=True); open('/usr/local/bin/gitea', 'wb').write(r.content)"

#Install custom theme
git clone https://git.bprieshof.nl/DarkTheme/Gitea-Arc_blue-Theme.git /opt/gitea_blue-theme/
ln -sfn /opt/gitea_blue-theme/custom_public_bin/css /var/lib/gitea/custom/public/css
ln -sfn /opt/gitea_blue-theme/custom_public_bin/js /var/lib/gitea/custom/public/js


#Moving configs in place
mv /opt/Setup/Configs/app.ini /etc/gitea/app.ini
mv /opt/Setup/Configs/auto-update.ini /etc/gitea/auto-update.ini
mv /opt/Setup/Configs/gitea.service /etc/init.d/gitea

#Set folder permissions 
chown -R git:git /gitea-data
chown -R git:git /var/log/gitea
chown -R git:git /var/lib/gitea/
chown -R root:git /etc/gitea
chmod -R 750 /var/lib/gitea/
chmod +x /usr/local/bin/gitea
chmod +x /etc/init.d/gitea
chmod 750 /etc/gitea
chmod 640 /etc/gitea/app.ini

#Fix Gitea-auto-updater to support OpenRC
sed -i -e 's/systemctl start gitea.service/service gitea start/' -e 's/systemctl stop gitea.service/service gitea stop/' /usr/lib/python3.*/site-packages/gitea_auto_update/update.py

#Gitea update Sript
echo "gitea-auto-update --settings=/etc/gitea/auto-update.ini" > /opt/UpdateGitea.sh