#!/bin/bash
#
# Gitea Service

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

config_gitea() {
  echo -ne "* Configuring gitea container.."

  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
  get_appvars

cat > /federated/apps/gitea/docker-compose.yml <<EOF
services:
  gitea:
    image: gitea/gitea:\${IMAGE_VERSION}
    container_name: gitea
    hostname: gitea.$DOMAIN
    restart: always
    networks:
      core:
        ipv4_address: 192.168.0.30
    extra_hosts:
      - "caddy.$DOMAIN:$EXTERNALIP"
      - "blog.$DOMAIN:$EXTERNALIP"
      - "documentation.$DOMAIN:$EXTERNALIP"
      - "authelia.$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:
  core:
    external: true
EOF

GITEA_SECRET=$(create_password);

[[ "${PLUS}" = "true" ]] && sed -i "s/letsencrypt/httpresolver/g" /federated/apps/gitea/docker-compose.yml

if [[ "${PLUS}" = "true" ]]; then
cat > /federated/apps/gitea/.env <<EOF
IMAGE_VERSION="$(current_version gitea)"
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=disable
GITEA__mailer__ENABLED=true
GITEA__mailer__FROM=gitea@gitea.$DOMAIN
GITEA__mailer__MAILER_TYPE=smtp
GITEA__mailer__SMTP_PORT=465
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
else
cat > /federated/apps/gitea/.env <<EOF
IMAGE_VERSION="$(current_version gitea)"
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=465
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
fi
chmod 600 /federated/apps/gitea/.env

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

# Create database and user in postgresql
docker exec postgresql psql -U postgres -c "CREATE USER gitea WITH PASSWORD '$GITEA_SECRET'" &> /dev/null
docker exec postgresql psql -U postgres -c "CREATE DATABASE gitea" &> /dev/null
docker exec postgresql psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE gitea TO gitea" &> /dev/null
 
echo -ne "done.\n"
}
email_gitea() {
  echo -ne "* Sending email to customer.."

cat > /federated/apps/mail/data/root/certs/mailfile <<EOF
<html>
<img src="https://www.federated.computer/wp-content/uploads/2023/11/logo.png" alt="" /><br>
<p>
<h4>Gitea is now installed on $DOMAIN</h4>
<p>
Here is your applications chart with on how to access this service:<br>
<p>
<h4>Applications</h4>
<style type="text/css">
.tg  {border-collapse:collapse;border-spacing:0;}
.tg td{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  overflow:hidden;padding:10px 5px;word-break:normal;}
.tg th{border-color:black;border-style:solid;border-width:1px;font-family:Arial, sans-serif;font-size:14px;
  font-weight:normal;overflow:hidden;padding:10px 5px;word-break:normal;}
.tg .tg-cul6{border-color:inherit;color:#340096;text-align:left;text-decoration:underline;vertical-align:top}
.tg .tg-acii{background-color:#FFF;border-color:inherit;color:#333;text-align:left;vertical-align:top}
.tg .tg-0hty{background-color:#000000;border-color:inherit;color:#ffffff;font-weight:bold;text-align:left;vertical-align:top}
.tg .tg-kwiq{border-color:inherit;color:#000000;text-align:left;vertical-align:top;word-wrap:break-word}
.tg .tg-0pky{border-color:inherit;text-align:left;vertical-align:top}
</style>
<table class="tg" style="undefined;table-layout: fixed; width: 996px">
<colgroup>
<col style="width: 101.333333px">
<col style="width: 203.333333px">
<col style="width: 282.333333px">
<col style="width: 185.33333px">
<col style="width: 78.333333px">
<col style="width: 220.333333px">
</colgroup>
<thead>
  <tr>
    <th class="tg-0hty">Service</th>
    <th class="tg-0hty">Link</th>
    <th class="tg-0hty">User / Pass</th>
    <th class="tg-0hty">Access</th>
    <th class="tg-0hty">Docs</th>
    <th class="tg-0hty">Description</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td class="tg-kwiq">Gitea</td>
    <td class="tg-kwiq"><a href="https://gitea.$DOMAIN" target="_blank" rel="noopener noreferrer"><span style="color:#340096">gitea.$DOMAIN</span></a></td>
    <td class="tg-kwiq">admin@$DOMAIN<br>admin password above</td>
    <td class="tg-kwiq">User access is separate from panel</td>
    <td class="tg-kwiq"><a href="https://documentation.federated.computer/docs/getting_started/welcome/" target="_blank" rel="noopener noreferrer"><span style="color:#340096">Click here</span></a></td>
    <td class="tg-kwiq">Gitea is a code repository system similar to GitHub</td>
  </tr>
</tbody>
</table>
<h4>Thanks for your support!</h4>
<p>
Thank you for your support of Federated Computer. We really appreciate it and hope you have a very successful
time with Federated Core.
<p>
Again, if we can be of any assistance, please don't hesitate to get in touch.
<p>
Support: https://support.federated.computer<br>
Phone: (970) 722-8715<br>
Email: support@federated.computer<br>
<p>
It's <b>your</b> computer. Let's make it work for you!
</html>
EOF

  # Send out e-mail from mail container with details
  docker exec mail bash -c "mail -r admin@$DOMAIN -a \"Content-type: text/html\" -s \"Application installed on $DOMAIN\" $EMAIL < /root/certs/mailfile"
  rm /federated/apps/mail/data/root/certs/mailfile

  echo -ne "done.\n"
}
uninstall_gitea() {
  echo -ne "* Uninstalling gitea container.."

  # First stop the service
  cd /federated/apps/gitea && docker compose -f docker-compose.yml -p gitea down &> /dev/null

  # Delete database and user in postgresql
  docker exec postgresql psql -U postgres -c "DROP DATABASE gitea" &> /dev/null
  docker exec postgresql psql -U postgres -c "DROP USER gitea" &> /dev/null

  # Delete the app directory
  rm -rf /federated/apps/gitea

  # Delete the image
  docker image rm gitea/gitea:$IMAGE_VERSION &> /dev/null

  # Delete the DNS record
  docker exec pdns pdnsutil delete-rrset $DOMAIN gitea A

  # Uninstall the SSO configuration if it exists in authelia (authelia must exist too)
  if [[ $(grep "### Gitea" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]]; then
    sed -i '/### Gitea/,/### /{/### PowerDNS/!{/### /!d}}' /federated/apps/authelia/data/config/idproviders.yml
    sed -i '/### Gitea/d' /federated/apps/authelia/data/config/idproviders.yml
    /federated/bin/stop authelia
    /federated/bin/start authelia
  fi

  [[ "${PLUS}" != "true" ]] && docker exec pdns pdnsutil delete-rrset $DOMAIN gitea A &> /dev/null

  echo -ne "done.\n"
}
start_gitea() {
  # Start service with command to make sure it's up before proceeding
  start_service "gitea" "nc -z 192.168.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"
  echo "$GITEA_TOKEN_1" > /federated/apps/gitea/.gitea.token.1

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

  [[ "${PLUS}" != "true" ]] && docker exec pdns pdnsutil add-record $DOMAIN gitea A 86400 $EXTERNALIP &> /dev/null

  echo -ne "done.\n"
}
configsso_gitea() {
  if [[ "${PLUS}" != "true" ]]; then
  echo -ne "* Configuring gitea container with SSO.."

  [ ! -d "/federated/apps/authelia" ] && failcheck "Authelia is not installed. You need this first before continuing."
  [ ! -f "/federated/apps/authelia/data/config/idproviders.yml" ] && failcheck "Authelia idproviders.yml is missing."
  [[ $(grep "### Gitea" /federated/apps/authelia/data/config/idproviders.yml 2>/dev/null) ]] && failcheck "Authelia already has a Gitea configuration."
  get_appvars

  GITEA_CLIENT_SECRET=$(create_password);
  GITEA_CLIENT_SECRET_HASH=$(docker run --rm authelia/authelia:latest authelia crypto hash generate pbkdf2 --password $GITEA_CLIENT_SECRET | awk '{ print $2 }')
  echo "$GITEA_CLIENT_SECRET" > /federated/apps/gitea/.gitea.client.secret

cat >> /federated/apps/authelia/data/config/idproviders.yml <<EOF
      ### Gitea
      - client_id: 'gitea'
        client_name: 'Gitea'
        client_secret: $GITEA_CLIENT_SECRET_HASH
        consent_mode: 'implicit'
        public: false
        authorization_policy: 'one_factor'
        redirect_uris:
          - 'https://gitea.$DOMAIN/user/oauth2/Authelia/callback'
        scopes:
          - 'openid'
          - 'profile'
          - 'email'
        userinfo_signed_response_alg: 'none'
        token_endpoint_auth_method: 'client_secret_basic'
EOF

  # Restart Authelia for changes to take the above configuration
  run_command "/federated/bin/stop authelia"
  run_command "/federated/bin/start authelia"

  # Add in extra hosts config
  add_authelia_config_to_dockercompose "gitea" "$EXTERNALIP"
  run_command "/federated/bin/stop gitea"
  run_command "/federated/bin/start gitea"

  sed -i "s/GITEA__service__DISABLE_REGISTRATION=.*/GITEA__service__DISABLE_REGISTRATION=false/g" /federated/apps/gitea/.env

cat >> /federated/apps/gitea/.env <<EOF
GITEA__openid__ENABLE_OPENID_SIGNIN=false
GITEA__openid__ENABLE_OPENID_SIGNUP=true
GITEA__openid__WHITELISTED_URIS=$DOMAIN
GITEA__service__ALLOW_ONLY_EXTERNAL_REGISTRATION=true
GITEA__service__SHOW_REGISTRATION_BUTTON=false
GITEA__oauth2_client__USERNAME=email
GITEA__oauth2_client__ACCOUNT_LINKING=login
GITEA__oauth2_client__OPENID_CONNECT_SCOPES="openid profile email"
EOF

  run_command "/federated/bin/stop gitea"
  run_command "/federated/bin/start gitea"

  GITEA_RETRY="0"
  until docker exec --user 1000 gitea gitea admin auth add-oauth --name "Authelia" --provider "openidConnect" --key "gitea" --secret "$GITEA_CLIENT_SECRET" --auto-discover-url "https://authelia.$DOMAIN/.well-known/openid-configuration" --skip-local-2fa "true" --scopes "openid email profile" --group-claim-name "groups" --admin-group "admin" --restricted-group "guest" &>/dev/null; do
    [[ "$GITEA_RETRY" -eq 60 ]] && echo "ERROR - Can't connect gitea add-oauth to authelia" && break
    sleep 1
    ((GITEA_RETRY++))
done

  echo -ne "done.\n"
  fi
}
configsso_gitea_plus() {
  GITEA_CLIENT_SECRET=$(cat /federated/apps/gitea/.gitea.client.secret)

  run_command "/federated/bin/stop gitea"
  run_command "/federated/bin/start gitea"

  sed -i "s/GITEA__service__DISABLE_REGISTRATION=.*/GITEA__service__DISABLE_REGISTRATION=false/g" /federated/apps/gitea/.env

cat >> /federated/apps/gitea/.env <<EOF
GITEA__openid__ENABLE_OPENID_SIGNIN=false
GITEA__openid__ENABLE_OPENID_SIGNUP=true
GITEA__openid__WHITELISTED_URIS=$DOMAIN
GITEA__service__ALLOW_ONLY_EXTERNAL_REGISTRATION=true
GITEA__service__SHOW_REGISTRATION_BUTTON=false
GITEA__oauth2_client__USERNAME=email
GITEA__oauth2_client__ACCOUNT_LINKING=login
GITEA__oauth2_client__OPENID_CONNECT_SCOPES="openid profile email"
EOF

  run_command "/federated/bin/stop gitea"
  run_command "/federated/bin/start gitea"

  GITEA_RETRY="0"
  until docker exec --user 1000 gitea gitea admin auth add-oauth --name "Authelia" --provider "openidConnect" --key "gitea" --secret "$GITEA_CLIENT_SECRET" --auto-discover-url "https://authelia.$DOMAIN/.well-known/openid-configuration" --skip-local-2fa "true" --scopes "openid email profile" --group-claim-name "groups" --admin-group "admin" --restricted-group "guest" &>/dev/null; do
    [[ "$GITEA_RETRY" -eq 60 ]] && echo "ERROR - Can't connect gitea add-oauth to authelia" && break
    sleep 1
    ((GITEA_RETRY++))
done

  echo -ne "done.\n"
}
