#!/bin/bash
# ============================================================
# Gitea (Git 서버) + SMTP (Postfix) 설치 스크립트
# Oracle Cloud Ubuntu 22.04 ARM (Ampere A1)
# 실행: bash 10_gitea_smtp_setup.sh [도메인]
# ============================================================

set -e
DOMAIN=${1:-"$(curl -s ifconfig.me)"}
GITEA_DOMAIN="git.${DOMAIN}"
GREEN='\033[0;32m'; CYAN='\033[0;36m'; YELLOW='\033[1;33m'; NC='\033[0m'
info()    { echo -e "${GREEN}[OK]${NC} $1"; }
section() { echo -e "\n${CYAN}════════════════════════════════${NC}"; echo -e "${CYAN} $1${NC}"; echo -e "${CYAN}════════════════════════════════${NC}"; }

# ────────────────────────────────────────────────
# PART 1: Gitea 설치
# ────────────────────────────────────────────────

section "1. Gitea 사용자 생성"
sudo adduser --system --shell /bin/bash --gecos 'Git Version Control' \
     --group --disabled-password --home /home/git git 2>/dev/null || true
info "git 사용자 준비 완료"

section "2. Gitea 바이너리 다운로드 (ARM64)"
GITEA_VER="1.22.3"
sudo mkdir -p /opt/gitea/bin
sudo wget -q "https://dl.gitea.com/gitea/${GITEA_VER}/gitea-${GITEA_VER}-linux-arm64" \
     -O /opt/gitea/bin/gitea
sudo chmod +x /opt/gitea/bin/gitea
sudo ln -sf /opt/gitea/bin/gitea /usr/local/bin/gitea
gitea --version
info "Gitea ${GITEA_VER} 다운로드 완료"

section "3. Gitea 디렉터리 구조"
sudo mkdir -p /var/lib/gitea/{custom,data,log}
sudo mkdir -p /etc/gitea
sudo chown -R git:git /var/lib/gitea /etc/gitea
sudo chmod -R 750 /var/lib/gitea /etc/gitea
info "Gitea 디렉터리 생성 완료"

section "4. Gitea PostgreSQL DB 생성"
sudo -u postgres psql <<PSQL 2>/dev/null || true
CREATE USER gitea WITH PASSWORD 'G1tea_2026!';
CREATE DATABASE gitea_db OWNER gitea;
GRANT ALL PRIVILEGES ON DATABASE gitea_db TO gitea;
PSQL
info "Gitea DB 생성 완료"

section "5. Gitea 설정 파일 생성"
sudo tee /etc/gitea/app.ini > /dev/null <<INI
[DEFAULT]
RUN_USER = git
RUN_MODE = prod

[database]
DB_TYPE  = postgres
HOST     = 127.0.0.1:5432
NAME     = gitea_db
USER     = gitea
PASSWD   = G1tea_2026!
SCHEMA   =
SSL_MODE = disable

[repository]
ROOT = /var/lib/gitea/data/repositories

[server]
SSH_DOMAIN       = ${GITEA_DOMAIN}
DOMAIN           = ${GITEA_DOMAIN}
HTTP_PORT        = 3000
ROOT_URL         = http://${GITEA_DOMAIN}/
DISABLE_SSH      = false
SSH_PORT         = 22
LFS_START_SERVER = true
OFFLINE_MODE     = false

[mailer]
ENABLED        = true
FROM           = noreply@${DOMAIN}
PROTOCOL       = smtp
SMTP_ADDR      = localhost
SMTP_PORT      = 25
IS_TLS_ENABLED = false

[service]
REGISTER_EMAIL_CONFIRM     = false
ENABLE_NOTIFY_MAIL         = true
DISABLE_REGISTRATION       = false
ALLOW_ONLY_EXTERNAL_REGISTRATION = false
ENABLE_CAPTCHA             = false
DEFAULT_KEEP_EMAIL_PRIVATE = true

[picture]
DISABLE_GRAVATAR = true

[log]
MODE      = file
LEVEL     = info
ROOT_PATH = /var/lib/gitea/log

[security]
INSTALL_LOCK       = false
SECRET_KEY         = $(openssl rand -hex 32)
INTERNAL_TOKEN     = $(openssl rand -hex 32)
INI

sudo chown git:git /etc/gitea/app.ini
sudo chmod 640 /etc/gitea/app.ini
info "Gitea 설정 파일 생성 완료"

section "6. Gitea systemd 서비스 등록"
sudo tee /etc/systemd/system/gitea.service > /dev/null <<SERVICE
[Unit]
Description=Gitea (Git with a cup of tea)
After=network.target postgresql.service

[Service]
RestartSec=2s
Type=simple
User=git
Group=git
WorkingDirectory=/var/lib/gitea/
ExecStart=/usr/local/bin/gitea web --config /etc/gitea/app.ini
Restart=always
Environment=USER=git HOME=/home/git GITEA_WORK_DIR=/var/lib/gitea
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
SERVICE

sudo systemctl daemon-reload
sudo systemctl enable gitea
sudo systemctl start gitea
sleep 5
sudo systemctl is-active gitea && info "Gitea 서비스 시작 완료" || echo "Gitea 시작 대기 중..."

# ────────────────────────────────────────────────
# PART 2: Postfix SMTP 설치
# ────────────────────────────────────────────────

section "7. Postfix SMTP 서버 설치"
# 비대화형 설치
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \
  postfix mailutils libsasl2-2 libsasl2-modules

sudo tee /etc/postfix/main.cf > /dev/null <<POSTFIX
# Postfix 기본 설정
smtpd_banner = \$myhostname ESMTP
biff = no
append_dot_mydomain = no

# 호스트명
myhostname = ${DOMAIN}
myorigin = /etc/mailname
mydestination = \$myhostname, localhost.\$mydomain, localhost

# 네트워크
inet_interfaces = loopback-only
inet_protocols = ipv4
mynetworks = 127.0.0.0/8

# 릴레이 (외부 메일 발송용 — Gmail SMTP 릴레이)
relayhost = [smtp.gmail.com]:587
smtp_sasl_auth_enable = yes
smtp_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_use_tls = yes
smtp_tls_CAfile = /etc/ssl/certs/ca-certificates.crt

# 메일함
mailbox_size_limit = 0
recipient_delimiter = +

# 보안
smtpd_relay_restrictions = permit_mynetworks permit_sasl_authenticated defer_unauth_destination
POSTFIX

# Gmail 릴레이 자격증명 (나중에 입력)
sudo tee /etc/postfix/sasl_passwd > /dev/null <<SASL
[smtp.gmail.com]:587 your-gmail@gmail.com:your-app-password
SASL
sudo chmod 600 /etc/postfix/sasl_passwd
sudo postmap /etc/postfix/sasl_passwd

echo "${DOMAIN}" | sudo tee /etc/mailname

sudo systemctl enable postfix
sudo systemctl restart postfix
info "Postfix SMTP 설치 완료"

# ────────────────────────────────────────────────
# PART 3: Nginx 설정 (Gitea)
# ────────────────────────────────────────────────

section "8. Gitea Nginx 역방향 프록시 설정"
sudo tee /etc/nginx/sites-available/gitea > /dev/null <<NGINX
server {
    listen 80;
    server_name ${GITEA_DOMAIN};

    client_max_body_size 512M;

    location / {
        proxy_pass         http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade \$http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host \$host;
        proxy_set_header   X-Real-IP \$remote_addr;
        proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto \$scheme;
        proxy_cache_bypass \$http_upgrade;
    }
}
NGINX

sudo ln -sf /etc/nginx/sites-available/gitea /etc/nginx/sites-enabled/gitea
sudo nginx -t && sudo systemctl reload nginx
info "Gitea Nginx 설정 완료"

# ────────────────────────────────────────────────
# 방화벽 업데이트
# ────────────────────────────────────────────────
section "9. 방화벽 규칙 업데이트"
sudo ufw allow 25/tcp    comment 'SMTP'
sudo ufw allow 587/tcp   comment 'SMTP TLS'
# Gitea는 Nginx 뒤에서 서빙 — 3000 포트 외부 차단
sudo ufw deny 3000/tcp

# Oracle Cloud 내부 iptables
sudo iptables -I INPUT 6 -m state --state NEW -p tcp --dport 25  -j ACCEPT
sudo iptables -I INPUT 6 -m state --state NEW -p tcp --dport 587 -j ACCEPT
sudo netfilter-persistent save
info "방화벽 업데이트 완료"

# ────────────────────────────────────────────────
# 완료 요약
# ────────────────────────────────────────────────
section "✅ Gitea + SMTP 설치 완료!"
echo ""
echo -e "${GREEN}서비스 접속 주소:${NC}"
echo "  Gitea:    http://${GITEA_DOMAIN}"
echo "  (IP직접): http://$(curl -s ifconfig.me):3000"
echo ""
echo -e "${YELLOW}⚠️  Gitea 초기 설정 (브라우저에서):${NC}"
echo "  1. http://${GITEA_DOMAIN} 접속"
echo "  2. 관리자 계정 생성"
echo "  3. GUARDiA 저장소 생성: guardia/guardia-itsm"
echo ""
echo -e "${YELLOW}⚠️  Gmail 앱 비밀번호 설정:${NC}"
echo "  1. Google 계정 → 보안 → 2단계 인증 활성화"
echo "  2. 앱 비밀번호 생성 → Postfix용"
echo "  3. sudo nano /etc/postfix/sasl_passwd"
echo "     [smtp.gmail.com]:587 your@gmail.com:앱비밀번호"
echo "  4. sudo postmap /etc/postfix/sasl_passwd"
echo "  5. sudo systemctl restart postfix"
