pipeline {
  agent any

  // Run once per day.
  triggers {
    // This is in UTC on jenkins-og.xarth.tv. 8:45 AM UTC is 1:45 AM PDT / 12:45 AM PST.
    cron('45 8 * * *')
  }

  // KEY1 matches the logsstats.sh script.
  // DONE is used to avoid running more than once per day.
  // ROLE has read access to cloudwatch logs for the eni(s) being scanned.
  environment {
    KEY1 = sh(script: "date '+%Y/%m/%d'", returnStdout: true).trim()
    PREV = sh(script: "tail -n1 docs/processed.txt", returnStdout: true).trim()
    LAST3 = sh(script: "tail -n3 docs/processed.txt | awk '{print \"docs/json/\" \$1 \"-daily.json\"}' | xargs | tr ' ' ','", returnStdout: true).trim()
    LAST6 = sh(script: "tail -n6 docs/processed.txt | awk '{print \"docs/json/\" \$1 \"-daily.json\"}' | xargs | tr ' ' ','", returnStdout: true).trim()
    DONE = sh(script: "grep -q $KEY1 docs/processed.txt", returnStatus: true)
    ROLE = "arn:aws:iam::007917851548:role/jenkins"
    GIT_SSH_COMMAND = "ssh -o StrictHostKeyChecking=no"
  }

  stages {
    stage('report') {
      when {
        beforeAgent true
        allOf {
          branch 'master'
          // Do not re-process a previously-processed day.
          environment name: 'DONE', value: '1'
        }
      }

      agent { docker {
        image 'docker.pkgs.xarth.tv/awsi/bionic/go1.17:latest'
      }}

      steps {
        withAWS(role: ROLE) { sshagent(credentials: ['git-aws-read-key']) {
          // Create a report _and_ output an aggregated json file.
          sh """
            mkdir -p "docs/{json,html}/${KEY1}"
            go get -u code.justin.tv/systems/find_ip_owner
            go mod tidy
            
            # Create a daily report from remote data. Save it as an html file and a json file.
            go run . -age 24h -html "docs/html/${KEY1}-daily" -json "docs/json/${KEY1}-daily.json"

            # Create an aggregate (almost all time) report. Save it as an html file and a json file.
            go run . -age 0s -load "docs/json/${PREV}.json,docs/json/${KEY1}-daily.json" -html "docs/html/${KEY1}" -json "docs/json/${KEY1}.json"

            # Create a report from last 6 days + today (for 7). No json file output.
            go run . -age 0s -load "${LAST6},docs/json/${KEY1}-daily.json" -html "docs/html/${KEY1}-last7"

            # Create a per-account report from last 3 days + today (for 4). No json file output.
            go run . -age 0s -type account -load "${LAST3},docs/json/${KEY1}-daily.json" -html "docs/html/${KEY1}"

            echo " <li><a href=\"html/${KEY1}/index.html\">${KEY1}</a> (per account);"    >> docs/index.html
            echo "     ALL: <a href=\"html/${KEY1}-daily.html\"> daily</a>,"              >> docs/index.html
            echo "     <a href=\"html/${KEY1}-last7.html\">last 7 days</a>,"              >> docs/index.html
            echo "     <a href=\"html/${KEY1}.html\">aggregate</a>,"                      >> docs/index.html
            echo "     <a href=\"html/${KEY1}-daily-baremetal.html\">baremetal</a>,"      >> docs/index.html
            echo "     <a href=\"html/${KEY1}-last7-baremetal.html\">BM last 7 days</a>," >> docs/index.html
            echo "     <a href=\"html/${KEY1}-baremetal.html\">baremetal aggregate</a>"   >> docs/index.html
          """
        }}

        // This read-key has write access to the repo.
        sshagent(credentials: ['git-aws-read-key']) {
          sh """
            echo "${KEY1}" >> docs/processed.txt
            git config --global user.email "do-not-reply@twitch.tv"
            git config --global user.name "Jenkins Auto Build"
            git config remote.origin.url git@git.xarth.tv:awsi/eniflowner.git
            git add docs
            git commit -m "Jenkins Processed ${KEY1}"
            git push origin HEAD:refs/heads/master --force
          """
        }
      }
    }
  }
}
