#!/bin/bash

# Ubuntuのリリース名を取得
RELEASE=$(lsb_release -cs)

# リリース名が空でないかチェック
if [[ -z "$RELEASE" ]]; then
    echo "Error: Unable to obtain Ubuntu release codename."
    exit 1
fi

# リポジトリファイルのダウンロード
if ! wget -q -O /tmp/ubuntu-ja.sources "https://www.ubuntulinux.jp/sources.list.d/$RELEASE.sources"; then
    echo "Error: Failed to download the repository file."
    exit 1
fi

# ファイルサイズが690バイト未満かチェック
if [[ $(stat -c %s /tmp/ubuntu-ja.sources) -lt 690 ]]; then
    echo "Error: The downloaded file is too small."
    rm -f /tmp/ubuntu-ja.sources
    exit 1
fi

# ダウンロードしたファイルが既存のファイルと同一であるかチェック
if [[ -f /etc/apt/sources.list.d/ubuntu-ja.sources ]] && cmp -s /tmp/ubuntu-ja.sources /etc/apt/sources.list.d/ubuntu-ja.sources; then
    echo "No changes in the repository file. No update needed."
    rm -f /tmp/ubuntu-ja.sources
    exit 0
fi

# ダウンロードしたファイルを所定の位置に移動
mv /tmp/ubuntu-ja.sources /etc/apt/sources.list.d/ubuntu-ja.sources

# APTのパッケージリストを更新
if ! apt-get update; then
    echo "Error: Failed to update package lists."
    exit 1
fi
