#!/usr/bin/env bash
set -euo pipefail

# Gitea Installation Script
# Installs Gitea to /home/mleku/gitea with SQLite backend

GITEA_VERSION="1.25.1"
GITEA_BASE_DIR="/home/mleku/gitea"
GITEA_USER="mleku"
ARCH="linux-amd64"

# Capture script directory before changing directories
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== Gitea Installation Script ===${NC}"
echo "Version: ${GITEA_VERSION}"
echo "Installation directory: ${GITEA_BASE_DIR}"
echo "User: ${GITEA_USER}"
echo ""

# Check if Git is installed
echo -e "${YELLOW}Checking prerequisites...${NC}"
if ! command -v git &> /dev/null; then
    echo -e "${RED}Error: Git is not installed. Please install Git first.${NC}"
    exit 1
fi

GIT_VERSION=$(git --version | awk '{print $3}')
echo "Git version: ${GIT_VERSION}"

# Create directory structure
echo -e "${YELLOW}Creating directory structure...${NC}"
mkdir -p "${GITEA_BASE_DIR}"/{bin,custom,data,log,tmp}
mkdir -p "${GITEA_BASE_DIR}/data/"{gitea-repositories,attachments,lfs,avatars}
mkdir -p "${GITEA_BASE_DIR}/custom/conf"

# Download Gitea binary
echo -e "${YELLOW}Downloading Gitea ${GITEA_VERSION}...${NC}"
cd /tmp
wget -O gitea "https://dl.gitea.com/gitea/${GITEA_VERSION}/gitea-${GITEA_VERSION}-${ARCH}" || {
    echo -e "${RED}Failed to download Gitea binary${NC}"
    exit 1
}

# Download GPG signature for verification (optional but recommended)
echo -e "${YELLOW}Downloading GPG signature...${NC}"
wget -O gitea.asc "https://dl.gitea.com/gitea/${GITEA_VERSION}/gitea-${GITEA_VERSION}-${ARCH}.asc" || {
    echo -e "${YELLOW}Warning: Could not download signature file${NC}"
}

# Verify GPG signature if signature file exists
if [ -f gitea.asc ]; then
    echo -e "${YELLOW}Verifying GPG signature (this may take a moment)...${NC}"
    # Try to import the Gitea signing key
    gpg --keyserver hkps://keys.openpgp.org --recv 7C9E68152594688862D62AF62D9AE806EC1592E2 2>/dev/null || {
        echo -e "${YELLOW}Warning: Could not import GPG key, skipping verification${NC}"
    }

    # Verify if key was imported
    if gpg --list-keys 7C9E68152594688862D62AF62D9AE806EC1592E2 &>/dev/null; then
        if gpg --verify gitea.asc gitea 2>&1 | grep -q "Good signature"; then
            echo -e "${GREEN}✓ GPG signature verified successfully${NC}"
        else
            echo -e "${RED}Warning: GPG signature verification failed${NC}"
            read -p "Continue anyway? (y/N) " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                exit 1
            fi
        fi
    fi
    rm -f gitea.asc
fi

# Make binary executable and move to installation directory
chmod +x gitea
mv gitea "${GITEA_BASE_DIR}/bin/gitea"
echo -e "${GREEN}✓ Binary installed to ${GITEA_BASE_DIR}/bin/gitea${NC}"

# Create initial app.ini configuration for SQLite
echo -e "${YELLOW}Creating initial configuration...${NC}"
cat > "${GITEA_BASE_DIR}/custom/conf/app.ini" << EOF
# Gitea Configuration
# Generated by giteainstall.sh

APP_NAME = Gitea: Git with a cup of tea
RUN_MODE = prod
RUN_USER = ${GITEA_USER}

[repository]
ROOT = ${GITEA_BASE_DIR}/data/gitea-repositories

[repository.local]
LOCAL_COPY_PATH = ${GITEA_BASE_DIR}/tmp/local-repo

[repository.upload]
TEMP_PATH = ${GITEA_BASE_DIR}/data/tmp/uploads

[server]
APP_DATA_PATH    = ${GITEA_BASE_DIR}/data
DOMAIN           = localhost
HTTP_PORT        = 3000
ROOT_URL         = http://localhost:3000/
DISABLE_SSH      = false
SSH_DOMAIN       = localhost
SSH_PORT         = 22
SSH_LISTEN_PORT  = 2222
LFS_START_SERVER = true
LFS_JWT_SECRET   = # Will be generated on first run
OFFLINE_MODE     = false

[database]
PATH     = ${GITEA_BASE_DIR}/data/gitea.db
DB_TYPE  = sqlite3
HOST     =
NAME     = gitea
USER     =
PASSWD   =
LOG_SQL  = false
SCHEMA   =
SSL_MODE = disable

[indexer]
ISSUE_INDEXER_PATH = ${GITEA_BASE_DIR}/data/indexers/issues.bleve
REPO_INDEXER_ENABLED = false

[session]
PROVIDER_CONFIG = ${GITEA_BASE_DIR}/data/sessions
PROVIDER = file

[picture]
AVATAR_UPLOAD_PATH            = ${GITEA_BASE_DIR}/data/avatars
REPOSITORY_AVATAR_UPLOAD_PATH = ${GITEA_BASE_DIR}/data/repo-avatars
DISABLE_GRAVATAR              = false
ENABLE_FEDERATED_AVATAR       = true

[attachment]
PATH = ${GITEA_BASE_DIR}/data/attachments

[log]
MODE      = console, file
LEVEL     = info
ROOT_PATH = ${GITEA_BASE_DIR}/log
ROUTER    = console

[security]
INSTALL_LOCK   = false
SECRET_KEY     = # Will be generated on first run
INTERNAL_TOKEN = # Will be generated on first run

[service]
DISABLE_REGISTRATION              = false
REQUIRE_SIGNIN_VIEW               = false
REGISTER_EMAIL_CONFIRM            = false
ENABLE_NOTIFY_MAIL                = false
ALLOW_ONLY_EXTERNAL_REGISTRATION  = false
ENABLE_CAPTCHA                    = false
DEFAULT_KEEP_EMAIL_PRIVATE        = false
DEFAULT_ALLOW_CREATE_ORGANIZATION = true
DEFAULT_ENABLE_TIMETRACKING       = true
NO_REPLY_ADDRESS                  = noreply.localhost

[mailer]
ENABLED = false

[openid]
ENABLE_OPENID_SIGNIN = true
ENABLE_OPENID_SIGNUP = true

[lfs]
PATH = ${GITEA_BASE_DIR}/data/lfs
EOF

echo -e "${GREEN}✓ Configuration created at ${GITEA_BASE_DIR}/custom/conf/app.ini${NC}"

# Set proper permissions
echo -e "${YELLOW}Setting permissions...${NC}"
chmod -R 755 "${GITEA_BASE_DIR}"
chmod 640 "${GITEA_BASE_DIR}/custom/conf/app.ini"

# Create systemd service file
SERVICE_FILE="${SCRIPT_DIR}/gitea.service"

echo -e "${YELLOW}Creating systemd service file...${NC}"
cat > "${SERVICE_FILE}" << 'EOFSERVICE'
[Unit]
Description=Gitea (Git with a cup of tea)
After=network.target
Wants=network.target

[Service]
Type=simple
User=mleku
Group=mleku
WorkingDirectory=/home/mleku/gitea
ExecStart=/home/mleku/gitea/bin/gitea web --config /home/mleku/gitea/custom/conf/app.ini
Restart=always
RestartSec=2s
Environment="USER=mleku" "HOME=/home/mleku" "GITEA_WORK_DIR=/home/mleku/gitea"

# Security enhancements
PrivateTmp=yes
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=no
ReadWritePaths=/home/mleku/gitea

# Limits
LimitNOFILE=65535
LimitNPROC=65535

[Install]
WantedBy=multi-user.target
EOFSERVICE

echo -e "${GREEN}✓ Service file created at ${SERVICE_FILE}${NC}"

# Summary
echo ""
echo -e "${GREEN}=== Installation Complete ===${NC}"
echo ""
echo "Installation directory: ${GITEA_BASE_DIR}"
echo "Binary location: ${GITEA_BASE_DIR}/bin/gitea"
echo "Configuration: ${GITEA_BASE_DIR}/custom/conf/app.ini"
echo "Database: ${GITEA_BASE_DIR}/data/gitea.db (SQLite)"
echo "Service file: ${SERVICE_FILE}"
echo ""
echo -e "${YELLOW}Next steps:${NC}"
echo ""
echo "1. Install the systemd service:"
echo "   sudo cp ${SERVICE_FILE} /etc/systemd/system/"
echo "   sudo systemctl daemon-reload"
echo ""
echo "2. Enable and start Gitea:"
echo "   sudo systemctl enable gitea"
echo "   sudo systemctl start gitea"
echo ""
echo "3. Check status:"
echo "   sudo systemctl status gitea"
echo ""
echo "4. View logs:"
echo "   sudo journalctl -u gitea -f"
echo ""
echo "5. Access Gitea at:"
echo "   http://localhost:3000"
echo ""
echo "6. Complete the installation wizard in your browser"
echo "   (Most settings are pre-configured for SQLite)"
echo ""
echo -e "${YELLOW}Note:${NC} The first time you access Gitea, you'll need to complete"
echo "the installation wizard to create the admin account."
echo ""
