#!/usr/bin/env nix-shell
#! nix-shell -i bash -p curl xmlstarlet nix coreutils 'python3.withPackages(ps: [ ps.packaging ])' nix-prefetch-git jq
set -euxo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
cd $SCRIPTPATH

function update_savannah_branch() {
    branch=$1
    echo emacs $branch

    url="https://https.git.savannah.gnu.org/git/emacs.git"

    # extract the latest commit sha
    commit_sha=$(git ls-remote --branches "$url" refs/heads/$branch | cut -f 1)

    source_info=$(nix-prefetch-git --rev $commit_sha "$url")

    digest=$(echo $source_info | jq -r .sha256)
    # build a version number based on date: YYYYMMDD.0
    version_number=$(echo $source_info | jq -r .date | cut -d 'T' -f 1 | sed 's/-//g').0
    output_branch=$(echo $branch | sed s/"\/"/"_"/)
    echo "{\"type\": \"savannah\", \"url\": \"${url}\", \"rev\": \"${commit_sha}\", \"sha256\": \"${digest}\", \"version\": \"${version_number}\"}" > emacs-$output_branch.json
}

function update_github_repo() {
    owner=$1
    repo=$2
    branch=$3
    output_name=$4
    echo $repo $branch

    # Get relevant data (commit id and timestamp) for the latest commit
    commit_data=$(curl "https://github.com/$owner/$repo/commits/$branch.atom" | xmlstarlet sel -N atom="http://www.w3.org/2005/Atom" -t -m /atom:feed/atom:entry -v "concat(atom:id,'/',atom:updated)" -n | head -n 1)

    # Extract commit sha and build a version number based on date: YYYYMMDD.0
    commit_sha=$(echo $commit_data | cut -d '/' -f 2)
    version_number=$(echo $commit_data | cut -d '/' -f 3 | cut -d 'T' -f 1 | sed 's/-//g').0

    digest=$(nix-prefetch-url --unpack "https://github.com/$owner/$repo/archive/${commit_sha}.tar.gz")
    echo "{\"type\": \"github\", \"owner\": \"${owner}\", \"repo\": \"${repo}\", \"rev\": \"${commit_sha}\", \"sha256\": \"${digest}\", \"version\": \"${version_number}\"}" > $repo-$output_name.json
}

function update_unstable() {
    echo emacs unstable
    python3 ./update-unstable.py
}

update_savannah_branch master
update_savannah_branch feature/igc3
update_unstable

nix-build --no-out-link --show-trace ./test.nix
