#!/bin/bash
set -e

# https://gist.github.com/siddharthkrish/32072e6f97d7743b1a7c47d76d2cb06c
increase_version () {
    version="$1"
    major=0
    minor=0
    build=0

    # break down the version number into it's components
    regex="v([0-9]+).([0-9]+).([0-9]+)"
    if [[ $version =~ $regex ]]; then
        major="${BASH_REMATCH[1]}"
        minor="${BASH_REMATCH[2]}"
        build="${BASH_REMATCH[3]}"
    else
        exit -1
    fi

    # check paramater to see which number to increment
    if [[ "$2" == "feature" ]]; then
        minor=$(echo $minor + 1 | bc)
    elif [[ "$2" == "bug" ]]; then
        build=$(echo $build + 1 | bc)
    elif [[ "$2" == "major" ]]; then
        major=$(echo $major+1 | bc)
    else
        exit -1
    fi

    echo "v${major}.${minor}.${build}"
}

apt update && apt install -y wget git jq curl git-lfs bc
wget -O ./GeoLite2-Country.tar.gz "https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-Country&license_key=${LICENSE_KEY}&suffix=tar.gz"
tar zxvf ./GeoLite2-Country.tar.gz -C .
mv ./GeoLite2-Country_*/GeoLite2-Country.mmdb ./Country.mmdb
wget -O ./GeoLite2-City.tar.gz "https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&license_key=${LICENSE_KEY}&suffix=tar.gz"
tar zxvf ./GeoLite2-City.tar.gz -C .
mv ./GeoLite2-City_*/GeoLite2-City.mmdb ./City.mmdb
wget -O ./GeoLite2-ASN.tar.gz "https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-ASN&license_key=${LICENSE_KEY}&suffix=tar.gz"
tar zxvf ./GeoLite2-ASN.tar.gz -C .
mv ./GeoLite2-ASN_*/GeoLite2-ASN.mmdb ./ASN.mmdb

url_host=`git remote get-url origin | sed -e "s/https:\/\/gitlab-ci-token:.*@//g"`
git remote set-url origin "https://gitlab-ci-token:${GITLAB_TOKEN}@${url_host}"
git config lfs.https://gitlab-ci-token:${GITLAB_TOKEN}@${url_host}/info/lfs.locksverify true
git config user.name  "leo108"
git config user.email "root@leo108.com"
git add ./Country.mmdb ./City.mmdb ./ASN.mmdb

if [[ -z $(git status -s -uno) ]]
then
  echo "No changes to MMDB"
  exit
fi

last_tag=$(curl -Ss --request GET "https://gitlab.com/api/v4/projects/${CI_PROJECT_ID}/repository/tags" | jq -r '.[0] | .name')
new_tag=$(increase_version $last_tag feature)

sed -i "s/\"version\": \".*\"/\"version\": \"${new_tag}\"/" package.json

git add package.json
git commit -m'Update GeoLite Database'
git push origin HEAD:master
git tag $new_tag
git push origin $new_tag

