diff --git a/tools/setup-qwiklabs.sh b/tools/setup-qwiklabs.sh index 518cbd24..00af09bd 100755 --- a/tools/setup-qwiklabs.sh +++ b/tools/setup-qwiklabs.sh @@ -17,24 +17,52 @@ while :; do shift done -if [ -z ${HACK} ] || [ -z ${SLUG} ]; then - echo "Usage: ${0} --hack= --slug=" 1>&2; exit 1 -fi +HACK="${HACK:-$1}" -if [[ ${SLUG} =~ ^ghacks[0-9]{3}$ ]]; then - SLUG=${SLUG}-${HACK} +if [ -z "${HACK}" ]; then + echo "Usage: ${0} [--slug=]" 1>&2; exit 1 fi -if [[ ! ${SLUG} =~ ^ghacks[0-9]{3}-${HACK}$ ]]; then - echo "Slug '${SLUG}' has to match pattern 'ghacks[0-9]{3}-${HACK}'" 1>&2; exit 1 -fi +# Sanitize in case a path is passed +HACK=$(basename "${HACK}") HACK_DIR="${SRC_DIR}/hacks/${HACK}" -if [ ! -d ${HACK_DIR} ] || [ ! -d ${DST_DIR} ]; then +if [ ! -d "${HACK_DIR}" ] || [ ! -d "${DST_DIR}" ]; then echo "${HACK_DIR} and/or ${DST_DIR} missing, are you in the right directory?" 1>&2; exit 1 fi +# If slug is not provided, find it or generate it (for new hacks) +if [ -z "${SLUG}" ]; then + # Check if there is an existing directory matching ghacks[0-9]{3}-${HACK} + EXISTING_DIR=$(ls "${DST_DIR}/labs" | grep -E "ghacks[0-9]{3}-${HACK}" | head -n 1) + + if [ -n "${EXISTING_DIR}" ]; then + SLUG="${EXISTING_DIR}" + echo "Found existing directory for hack '${HACK}': ${SLUG}" + else + # Detect the latest ghacks number in the target repository and increment it + LATEST_NUM=$(ls "${DST_DIR}/labs" | grep -E "ghacks[0-9]{3}-*" | \ + sed -E 's/^ghacks([0-9]{3})-.*/\1/' | sort -n | tail -n 1) + if [ -z "${LATEST_NUM}" ]; then + NEXT_NUM=1 + else + NEXT_NUM=$((10#${LATEST_NUM} + 1)) + fi + SLUG=$(printf "ghacks%03d-${HACK}" ${NEXT_NUM}) + echo "Detected next slug: ${SLUG}" + fi +else + if [[ ${SLUG} =~ ^ghacks[0-9]{3}$ ]]; then + SLUG=${SLUG}-${HACK} + fi + + if [[ ! ${SLUG} =~ ^ghacks[0-9]{3}-${HACK}$ ]]; then + echo "Slug '${SLUG}' has to match pattern 'ghacks[0-9]{3}-${HACK}'" 1>&2; exit 1 + fi +fi + + LAB_DIR="${DST_DIR}/labs/${SLUG}" mkdir -p ${LAB_DIR} @@ -58,6 +86,7 @@ BLOCK=`cat< +Latest instructions: https://ghacks.dev/hacks/${HACK} $OUTPUTS EOF