#!/bin/bash

# Check if Gitea is installed by checking for the systemd service or binary
#if systemctl is-active --quiet gitea || [ -f /usr/local/bin/gitea ]; then
#    echo "Gitea is already installed. Exiting installation."
#    exit 0
#fi

# Check if Gitea is installed
if systemctl is-active --quiet gitea || [ -f /usr/local/bin/gitea ]; then
    echo "Uninstalling existing Gitea installation..."

    # Stop the Gitea service
    sudo systemctl stop gitea

    # Disable the Gitea service from starting automatically
    sudo systemctl disable gitea

    # Remove the Gitea binary
    sudo rm -f /usr/local/bin/gitea

    # Remove Gitea systemd service file
    sudo rm -f /etc/systemd/system/gitea.service

    # Reload systemd daemon to apply changes
    sudo systemctl daemon-reload

    # Remove Gitea directories (Optional: You can keep data or backup)
    sudo rm -rf /var/lib/gitea
    echo "Gitea uninstalled successfully."
else
    echo "Gitea is not installed."
fi

# Update system packages
sudo apt update -y
sudo apt upgrade -y

# Install dependencies
sudo apt install -y git wget curl lsb-release sqlite3

# Set the Gitea version
GITEA_VERSION="1.23.5"  # Replace with the latest version if needed

# Download Gitea binary
# wget -O /tmp/gitea https://dl.gitea.com/gitea/${GITEA_VERSION}/gitea-${GITEA_VERSION}-linux-amd64

wget -O  /tmp/gitea https://github.com/go-gitea/gitea/releases/download/v1.23.5/gitea-1.23.5-linux-amd64

chmod +x /tmp/gitea

# Move Gitea binary to /usr/local/bin
sudo mv /tmp/gitea /usr/local/bin/gitea

# Create necessary directories
#sudo mkdir -p /var/lib/gitea/{custom,data,log}

# Create necessary directories for Gitea (custom, data, log)
sudo mkdir -p /var/lib/gitea/custom /var/lib/gitea/data /var/lib/gitea/log

sudo chown -R $USER:$USER /var/lib/gitea
sudo chmod -R 755 /var/lib/gitea

sudo mkdir /etc/gitea
chown root:git /etc/gitea
chmod 770 /etc/gitea

# chmod 750 /etc/gitea
# chmod 640 /etc/gitea/app.ini

# Create a system user for Gitea
sudo useradd --system --create-home --shell /bin/bash --comment 'Gitea' gitea

# Setup systemd service for Gitea
cat <<EOF | sudo tee /etc/systemd/system/gitea.service
[Unit]
Description=Gitea
After=network.target

[Service]
ExecStart=/usr/local/bin/gitea web
Restart=always
User=gitea
Group=gitea
Environment=USER=gitea HOME=/var/lib/gitea GITEA_WORK_DIR=/var/lib/gitea/data

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd to recognize the new service
sudo systemctl daemon-reload

# Enable and start Gitea service
sudo systemctl enable gitea
sudo systemctl start gitea

# Output the status of Gitea service
sudo systemctl status gitea

# Display message for post-installation configuration
echo "Gitea is installed and running. You can access it at http://<your_server_ip>:3000"