#@ load("@ytt:data", "data")

#@ ns = data.values.application.namespace

#@ s3_endpoint = data.values.backups.s3.endpoint
#@ s3_bucket = data.values.forgejo.backup.s3Bucket

#@ backup_script = """\
#@ set -e
#@ apk add --no-cache rclone > /dev/null 2>&1
#@
#@ mkdir -p /tmp/rclone
#@ cat > /tmp/rclone/rclone.conf <<CONF
#@ [s3]
#@ type = s3
#@ provider = Other
#@ access_key_id = ${ACCESS_KEY_ID}
#@ secret_access_key = ${SECRET_ACCESS_KEY}
#@ endpoint = """ + s3_endpoint + """
#@ acl = private
#@ CONF
#@
#@ echo "Syncing git repositories to S3..."
#@ rclone sync /data/git/ s3:""" + s3_bucket + """/forgejo/git/ \\
#@   --config /tmp/rclone/rclone.conf \\
#@   --transfers 4 \\
#@   -v
#@
#@ echo "Syncing gitea data (avatars, attachments, keys)..."
#@ rclone sync /data/gitea/ s3:""" + s3_bucket + """/forgejo/gitea/ \\
#@   --config /tmp/rclone/rclone.conf \\
#@   --exclude 'conf/**' \\
#@   --exclude 'queues/**' \\
#@   --transfers 4 \\
#@   -v
#@
#@ rm -rf /tmp/rclone
#@ echo "Backup complete."
#@ """

#@ if data.values.backups.enabled:
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: forgejo-git-backup
  namespace: #@ ns

---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: forgejo-git-backup
  namespace: #@ ns
spec:
  schedule: "0 3 * * *"
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 3
  jobTemplate:
    spec:
      ttlSecondsAfterFinished: 86400
      template:
        spec:
          restartPolicy: OnFailure
          serviceAccountName: forgejo-git-backup
          nodeSelector: #@ data.values.forgejo.nodeSelector
          containers:
            - name: backup
              image: alpine:3.20
              command:
                - sh
                - -c
                - #@ backup_script
              env:
                - name: ACCESS_KEY_ID
                  valueFrom:
                    secretKeyRef:
                      name: forgejo-backup-s3
                      key: ACCESS_KEY_ID
                - name: SECRET_ACCESS_KEY
                  valueFrom:
                    secretKeyRef:
                      name: forgejo-backup-s3
                      key: SECRET_ACCESS_KEY
              volumeMounts:
                - name: data
                  mountPath: /data
                  readOnly: true
          volumes:
            - name: data
              persistentVolumeClaim:
                claimName: forgejo-git-storage
#@ end
