#!/bin/bash
#
# Gitea Service

PATH=$HOME/.docker/cli-plugins:/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

config_gitea() {
  echo -ne "\n* Configuring /federated/apps/gitea container.."
  spin &
  SPINPID=$!

  if [ ! -d "/federated/apps/gitea" ]; then
    mkdir -p /federated/apps/gitea/data/data
    mkdir -p /federated/apps/gitea/data/data/git/.ssh
    touch /federated/apps/gitea/data/data/git/.ssh/authorized_keys
    chmod 600 /federated/apps/gitea/data/data/git/.ssh/authorized_keys
  fi

cat > /federated/apps/gitea/docker-compose.yml <<EOF
version: "3.7"

services:
  gitea:
    image: gitea/gitea:\${IMAGE_VERSION}
    container_name: gitea
    hostname: gitea.$DOMAIN
    domainname: $DOMAIN
    restart: always
    networks:
      federated:
        ipv4_address: 172.99.0.30
    extra_hosts:
      - "caddy.$DOMAIN:$EXTERNALIP"
      - "blog.$DOMAIN:$EXTERNALIP"
      - "documentation.$DOMAIN:$EXTERNALIP"
    ports:
      - "2222:22"
    env_file:
      - ./.env
    volumes:
      - ./data/data:/data
      - ./data/data/git/.ssh:/data/git/.ssh
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.gitea.rule=Host(\`gitea.$DOMAIN\`)"
      - "traefik.http.routers.gitea.entrypoints=websecure"
      - "traefik.http.routers.gitea.tls.certresolver=letsencrypt"
      - "traefik.http.services.gitea.loadbalancer.server.port=3000"

networks:
  federated:
    external: true
EOF

cat > /federated/apps/gitea/.env <<EOF
IMAGE_VERSION="1.19.0"
USER_UID=1000
USER_GID=1000
GITEA__database__DB_TYPE=postgres
GITEA__database__HOST=postgresql.$DOMAIN:5432
GITEA__database__NAME=gitea
GITEA__database__USER=gitea
GITEA__database__PASSWD=$GITEA_SECRET
GITEA__database__SSL_MODE=verify-full
GITEA__mailer__ENABLED=true
GITEA__mailer__FROM=gitea@gitea.$DOMAIN
GITEA__mailer__MAILER_TYPE=smtp
GITEA__mailer__SMTP_PORT=587
GITEA__mailer__HOST=mail.$DOMAIN
GITEA__mailer__IS_TLS_ENABLED=true
GITEA__mailer__USER=fcore
GITEA__mailer__PASSWD=$ADMINPASS
GITEA__security__INSTALL_LOCK=true
GITEA__server__ROOT_URL=https://gitea.$DOMAIN
GITEA__server__DOMAIN=$DOMAIN
GITEA__server__SSH_DOMAIN=$DOMAIN
GITEA__server__SSH_PORT=2222
GITEA__server__SSH_LISTEN_PORT=2222
GITEA__service__DISABLE_REGISTRATION=true
EOF
chmod 600 /federated/apps/gitea/.env

WEBHOOK_SECRET=$(create_password);

cat > /federated/apps/gitea/data/creategitea.sh <<EOF
#!/bin/bash

# Get the Gitea API token
GITEA_TOKEN_2=\`curl -H "Content-Type: application/json" -d '{"name":"gitea2","scopes":["all"]}' -u gitea:$ADMINPASS http://gitea.$DOMAIN:3000/api/v1/users/gitea/tokens 2>/dev/null | awk -F: '{ print \$4 }' | awk -F\" '{ print \$2 }'\`

# Create the repository website, blog, and documentation
curl -k -X POST http://gitea.$DOMAIN:3000/api/v1/user/repos -H "content-type: application/json" -H "Authorization: token \$GITEA_TOKEN_2" --data '{"name":"www","auto_init":true,"default_branch":"master","private":true}'
curl -k -X POST http://gitea.$DOMAIN:3000/api/v1/user/repos -H "content-type: application/json" -H "Authorization: token \$GITEA_TOKEN_2" --data '{"name":"blog","auto_init":true,"default_branch":"master","private":true}'
curl -k -X POST http://gitea.$DOMAIN:3000/api/v1/user/repos -H "content-type: application/json" -H "Authorization: token \$GITEA_TOKEN_2" --data '{"name":"documentation","auto_init":true,"default_branch":"master","private":true}'

# Create the webhook inside the www repository
curl -X 'POST' \
  'http://gitea.$DOMAIN:3000/api/v1/repos/gitea/www/hooks' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -H "Authorization: token \$GITEA_TOKEN_2" \
  -d '{
  "active": true,
  "config": {
    "content_type": "json",
    "url": "https://caddy.$DOMAIN/webhook",
    "secret": "$WEBHOOK_SECRET"
  },
  "events": [
    "push"
  ],
  "type": "gitea"
}'

# Create the webhook inside the blog repository
curl -X 'POST' \
  'http://gitea.$DOMAIN:3000/api/v1/repos/gitea/blog/hooks' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -H "Authorization: token \$GITEA_TOKEN_2" \
  -d '{
  "active": true,
  "config": {
    "content_type": "json",
    "url": "https://blog.$DOMAIN/webhook",
    "secret": "$WEBHOOK_SECRET"
  },
  "events": [
    "push"
  ],
  "type": "gitea"
}'

# Create the webhook inside the documentation repository
curl -X 'POST' \
  'http://gitea.$DOMAIN:3000/api/v1/repos/gitea/documentation/hooks' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -H "Authorization: token \$GITEA_TOKEN_2" \
  -d '{
  "active": true,
  "config": {
    "content_type": "json",
    "url": "https://documentation.$DOMAIN/webhook",
    "secret": "$WEBHOOK_SECRET"
  },
  "events": [
    "push"
  ],
  "type": "gitea"
}'
EOF

chmod +x /federated/apps/gitea/data/creategitea.sh
 
kill -9 $SPINPID &> /dev/null
echo -ne "done."
}
start_gitea() {
  # Start service with command to make sure it's up before proceeding
  start_service "gitea" "nc -z 172.99.0.30 3000 &> /dev/null" "7"

  # Copy creategitea.sh inside gitea container
  mv /federated/apps/gitea/data/creategitea.sh /federated/apps/gitea/data/data/creategitea.sh
  [ $? -ne 0 ] && fail "Couldn't mv creategitea.sh inside /federated/apps/gitea container"

  # Create admin user gitea
  docker exec --user 1000 gitea gitea admin user create --admin --username gitea --password $ADMINPASS --email admin@$DOMAIN &> /dev/null
  [ $? -ne 0 ] && fail "Couldn't run gitea user create inside /federated/apps/gitea container"

  # Run creategitea.sh inside gitea container
  docker exec gitea /data/creategitea.sh &> /dev/null
  [ $? -ne 0 ] && fail "Couldn't run creategitea.sh inside /federated/apps/gitea container"

  # Create token to use for Caddy starting up next
  GITEA_TOKEN_1=`docker exec gitea curl -H "Content-Type: application/json" -d '{"name":"gitea1","scopes":["all"]}' -u gitea:$ADMINPASS http://gitea.$DOMAIN:3000/api/v1/users/gitea/tokens 2>/dev/null | awk -F: '{ print $4 }' | awk -F\" '{ print $2 }'` &> /dev/null
  [ $? -ne 0 ] && fail "Couldn't run gitea curl to get token inside /federated/apps/gitea container"

  # Remove creategitea.sh
  rm /federated/apps/gitea/data/data/creategitea.sh

  kill -9 $SPINPID &> /dev/null
  echo -ne "done."
}
