#!/bin/bash

set -o errexit

VERSION="$1"
ACK="${2:-0}"
MIN_VERSION=2
MAX_VERSION=6

LINUX_URL=https://cdn.kernel.org/pub/linux/kernel
ACK_URL=https://android.googlesource.com/kernel/common/+archive/refs/heads

if [ -z "$VERSION" ]; then
    echo "usage: $0 VERSION [0 | 1]"
    exit 1
fi

if [ $ACK -eq 0 ]; then
    first_char=${VERSION:0:1}

    # Strip any leading 'v'
    if [ $first_char == v ]; then
        VERSION=${VERSION:1}
    fi
    first_char=${VERSION:0:1}

    # If patch version is 'y', we need to find the latest version of the major.minor release
    last_char=${VERSION: -1:1}
    if [ $last_char == y ]; then
        major_minor=${VERSION: 0:-1}
        VERSION=$(curl -s $LINUX_URL/v${first_char}.x/ \
                      | sed -e 's/<[^>]*>//g' \
                      | grep -oP "linux-${major_minor}[0-9]+" \
                      | sort -r -V \
                      | head -n1 \
                      | cut -d '-' -f2)
    fi

    echo "Downloading kernel version $VERSION"

    if [ $first_char -ge $MIN_VERSION ] && [ $first_char -le $MAX_VERSION ]; then
        wget --no-verbose --show-progress --progress=bar:force $LINUX_URL/v${first_char}.x/linux-$VERSION.tar.xz
        tar -xf linux-$VERSION.tar.xz
    else
        echo "$first_char is not a valid kernel major version number"
        exit 1
    fi
else
    wget --no-verbose --show-progress --progress=bar:force $ACK_URL/$VERSION.tar.gz
    mkdir -p $VERSION
    tar -xf $VERSION.tar.gz -C $VERSION
fi
